我正在尝试使用以下代码检查一个字符串是否与另一个字符串相同,或者它是否是其中的一部分:
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)
有什么问题吗?我怎样才能让它发挥作用?
最佳答案
我认为你需要使用nextLine(),而不是next()。 如:
String check = queries.nextLine();
和:
String toCheck = folks.nextLine();
因为默认分隔符是空格,所以如果文件末尾有空行(可能还有其他内容),则可能没有 next(),即使 hasNextLine() 返回 true。始终使用与您正在使用的 next*() 相对应的 hasNext*() 方法 - (反之亦然;-))。
关于java - 检查一个字符串是否等于另一个字符串或另一个字符串的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7488478/