Java 使用线性搜索检查?
我试图比较一个包含单词列表的.txt文件和一个同样填充单词的字符串[]数组Java 使用线性搜索检查?,java,arrays,string,Java,Arrays,String,我试图比较一个包含单词列表的.txt文件和一个同样填充单词的字符串[]数组 解决了,谢谢。假设您最终只是尝试获取两个文件中的单词列表: Scanner fileReader = new Scanner(file); Set<String> words = new HashSet<>(); while (fileReader.hasNext()) { String s = fileReader.next(); words.add(s); } fileReader.
解决了,谢谢。假设您最终只是尝试获取两个文件中的单词列表:
Scanner fileReader = new Scanner(file);
Set<String> words = new HashSet<>();
while (fileReader.hasNext()) {
String s = fileReader.next();
words.add(s);
}
fileReader.close();
Scanner otherFileReader = new Scanner(otherFile);
List<String> wordsInBothFiles = new ArrayList<>();
while (otherFileReader.hasNext()) {
String s = otherFileReader.next();
if (words.contains(s)) {
wordsInBothFiles.add(s);
}
}
otherFileReader.close();
// Do whatever it is you have to do with the shared words, like printing them:
// for (String s : wordsInBothFiles) {
// System.out.println(s);
// }
Scanner fileReader=新的扫描仪(文件);
Set words=新HashSet();
while(fileReader.hasNext()){
字符串s=fileReader.next();
字。加上(s);
}
fileReader.close();
Scanner otherFileReader=新扫描仪(otherFile);
List wordsInBothFiles=new ArrayList();
while(otherFileReader.hasNext()){
字符串s=otherFileReader.next();
如果(包含字){
两个文件中的字。添加;
}
}
otherFileReader.close();
//对共享的单词做任何你必须做的事情,比如打印它们:
//for(字符串s:wordsInBothFiles){
//系统输出打印项次;
// }
如果您选中该选项,它通常会解释方法引发异常的原因。在本例中,“未找到行”表示您已到达文件末尾。此错误有两种可能发生的方式:
String nextLine = scanner.nextLine(); //problem 1: reads a file with no lines
while (scanner.hasNextLine()) {
linearSearch(words,nextLine);
System.out.println(nextLine);
}
scanner.nextLine(); //problem 2: reads after there is not next line
由于您的循环看起来是无限的,我敢打赌您从第一行得到了异常,可以通过在String nextLine=scanner.nextLine()之前添加以下检查来修复它代码>:
除此之外,您可能还有一些其他问题,但希望这能解决您当前的问题。错误在哪一行?错误在“scanner.nextLine();”行上。很遗憾,我们无法使用Set/HashSet。有其他选择吗?您可以使用List/ArrayList,因为它还有一个.contains()
方法。我们也不能使用List/ArrayList。我应该提到的,对不起。
if(!scanner.hasNextLine()) {
System.out.println("empty file: "+filePath)
return; //or break or otherwise terminate
}