问题
How can I find the longest word in a text file? I am currently using the following method but I keep getting errors and don't know how to go forward after this.
public static String the_Longest(String text)throws IOException {
text = text.toLowerCase();
String longest =" ";
Scanner s = new Scanner(new File(text));
ArrayList<String>long_word=new ArrayList<String>();
while (s.hasNext()){
long_word.add(s.next());
}
s.close();
}
回答1:
You can use the same loop that you read the file to compare and select the longest string in the length, like this
public static String findLongest(String fileName) throws IOException {
Scanner scanner = new Scanner(new File(fileName.toLowerCase()));
String longest = "", next;
while (scanner.hasNext()) {
next = scanner.next();
if (longest.length() < next.length()) {
longest = next;
}
}
scanner.close();
return longest;
}
回答2:
It is analogous to finding the largest number from an array/list of numbers and therefore the same algorithm can be applied in this case.
- Store the first word from the file into
longest
. - Read the next words from the file in a loop. In each iteration of the loop, compare the length of
longest
with the word and replace the value oflongest
with the word ifword.length() > longest.length()
. - Return
longest
when the loop terminates.
Code:
public static String the_Longest(String text) throws IOException {
text = text.toLowerCase();
String longest = "", word;
Scanner s = new Scanner(new File(text));
if (s.hasNext()) {
longest = s.next();
}
while (s.hasNext()) {
word = s.next();
if (word.length() > longest.length()) {
longest = word;
}
}
s.close();
return longest;
}
来源:https://stackoverflow.com/questions/61718846/find-the-longest-and-shortest-words-in-a-text-file-using-methods