问题描述
我正在编写的代码是让用户在文本文件中搜索名称,如果在文件中找到该名称,则程序将输出“找到名称”。
然后,我只需要程序在文件中输出最短和最长的名称,这显然是我不知道该怎么做的事情。 这是我到目前为止所拥有的,但我无法使其正常工作。
只是想弄清楚编程不是我的强项,所以我的代码可能有点草率。 任何帮助将不胜感激。
码:
import java.util.*;
import java.io.*;
public class Homework11 {
public static void main(String args[]) throws IOException {
Scanner fileScan = new Scanner(new File("names.txt"));
Scanner keyboard = new Scanner(System.in);
// resets the Scanner to look for commas as
// the separator between the color names
fileScan.useDelimiter(",");
// initial capacity by default is 10 items
ArrayList<String> names = new ArrayList<String>();
while (fileScan.hasNext()) {
// each color read from the file is added to the ArrayList
names.add(fileScan.next());
}
// dump all the color names into a standard array of Strings
String namesArray[] = names.toArray(new String[0]);
// sort the color array into alphabetical order
Arrays.sort(namesArray);
for (int i = 0; i < namesArray.length; i++) {
// copy the array values back, overwriting the ArrayList
names.set(i, namesArray[i]);
}
System.out.println("Please enter a name to search.");
String input = keyboard.next();
String x = input.toUpperCase();
if (names.contains(x)) {
System.out.println("Name Found.");
}
}
}
1楼
在您的for循环之前添加以下代码段:
//set the default values
int longLength = namesArray[0].length;
int shortLength = namesArray[0].length;
String longName = namesArray[0];
String shortName = namesArray[0];
//check if any element is better than the current best
for (int i=1; i < namesArray.length; i++) {
if(namesArray[i].length > longLength){
longLength = namesArray[i].length;
longName = namesArray[i];
}
if(namesArray[i].length < shortLength){
shortLength = namesArray[i].length;
shortName = namesArray[i];
}
}
然后,您可以通过输出longName / shortName来输出最长/最短名称。