我正在尝试检查一个字符串是否与另一个字符串相同,或者如果它是以下代码的一部分:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class Comparison {
static void compare() throws FileNotFoundException {
Scanner queries = new Scanner(new FileReader("./out.txt"));
Scanner folks = new Scanner(new FileReader("./tal.txt"));
int index1 = 0;
while ( queries.hasNextLine() ){
String check = queries.next();
while (folks.hasNextLine()) {
String toCheck = folks.next();
index1 = toCheck.indexOf(check);
}//while
}//while
System.out.println("Result: "+ index1);
}
}
但我收到以下错误:
Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:838) at java.util.Scanner.next(Scanner.java:1347) at results.Comparison.compare(Comparison.java:28) at results.Main.main(Main.java:42)
有什么问题?我怎样才能使它发挥作用?
答案 0 :(得分:2)
我认为你需要使用nextLine(),而不是next()。 如:
String check = queries.nextLine();
和
String toCheck = folks.nextLine();
因为默认分隔符是空格,如果文件末尾有空行(可能还有其他内容),则可能没有next(),即使hasNextLine()返回true。始终使用与您正在使用的下一个*()对应的hasNext *()方法 - (反之亦然; - ))。
答案 1 :(得分:1)
folks
的初始化需要在外部循环中,例如:
Scanner queries = new Scanner(new FileReader("./out.txt"));
int index1 = 0;
while ( queries.hasNextLine() ){
String check = queries.next();
Reader r = new FileReader("./tal.txt");
try {
Scanner folks = new Scanner(r);
while (folks.hasNextLine()) {
String toCheck = folks.next();
index1 = toCheck.indexOf(check);
if (index1 >= 0) {
// Do something with index1 here?
}
}//while
} finally {
r.close();
}
}//while