gpt4 book ai didi

java - 检查一个字符串是否相等或另一个字符串的子字符串

转载 作者:行者123 更新时间:2023-12-04 06:13:53 24 4
gpt4 key购买 nike

我正在尝试使用以下代码检查一个字符串是否与另一个字符串相同,或者它是否是其中的一部分:

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);
}
}

但我收到以下错误:

线程“main”中的异常 java.util.NoSuchElementException
在 java.util.Scanner.throwFor(Scanner.java:838)
在 java.util.Scanner.next(Scanner.java:1347)
在 results.Comparison.compare(Comparison.java:28)
在 results.Main.main(Main.java:42)

问题是什么?我怎样才能让它工作?

最佳答案

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

关于java - 检查一个字符串是否相等或另一个字符串的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7488478/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com