import java.io.*;
import java.util.*;
public class Hellno {
public static void main(String[] args) {
try {
Scanner s = new Scanner(new File("words.txt"));
findBiggest(s);
System.out.println(findBiggest(s));
} catch (IOException e) {
System.out.println("Can't find that file");
}
}
public static String findBiggest(Scanner scan) {
int count0 = 0;
int count1 = 0;
String srs = "";
while (scan.hasNext()) { //how do i make this the longest?
String nsrs = scan.next();
count0 = nsrs.length();
if (count0 > count1) { // if the new length is bigger than what was solidified
count1 = count0; //new solidification of number
count0 = 0; // count becomes 0 to start again
srs = nsrs; // nsrs has been solidified as the new biggest String
}
else if (count0 <= count1) { // if the new length is smaller than what was solidified
count0 = 0; //then we start again with dummyCount = 0;
}
}
return srs;}}
我正在尝试从文本文件中读取,找出最长的字符串并返回该字符串。但是,这个编码忽略了所有while()并且似乎跳转到返回srs。为什么?
答案 0 :(得分:6)
您在同一个findBiggest
上拨打Scanner
两次。第一次调用可能找到了最大的单词并将其返回,但它被忽略了。第二个调用找不到任何单词,while
循环没有迭代。
只需拨打findBiggest
一次。
Scanner s = new Scanner(new File("words.txt"));
System.out.println(findBiggest(s));
答案 1 :(得分:0)
需要在扫描仪上设置分隔符
Scanner s = new Scanner(input).useDelimiter(System.getProperty("line.separator"));