我正在尝试制作一个拼写检查器,并打算在链接列表中打开 .txt 文件中的单词,但 hasNextLine() 始终返回 false。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.Scanner;
public class backEnd {
String string;
String[] splitted;
public backEnd(String s){
string=s;
}
public void splitter(){
splitted =string.split(" ");
for (int x=0; x<splitted.length; x++){
System.out.println(splitted[x]);
}
}
public void spellChecker(){
Serializable data = new String[100];
LinkedList<String> l=new LinkedList<String>();
File f= new File("WordDict.txt");
if(!f.exists())
try {
f.createNewFile();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
FileInputStream Fis=new FileInputStream(f);
Scanner sc = new Scanner(Fis);
System.out.println("Check outside nextline");
这是应该从 .txt 文件中逐行获取单词的点,但它总是会中断循环。
while (sc.hasNextLine()){
System.out.println("Check in nextline");
data = sc.nextLine();
l.add( (String) data);
}
sc.close();
}
catch(FileNotFoundException fnf){
fnf.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("\nProgram terminated Safely...");
}
int x=0;
int y=0;
while(x<splitted.length){
while(y<l.size()){
if(l.get(y)==splitted[x]){
System.out.println("Matched.");
y++;
}`enter code here`
}
System.out.println("Wrong spelling of: "+splitted[x]);
x++;
}
}
}
最佳答案
明显的原因似乎是文件WordDict.txt
不存在,
所以你的代码创建了它,但它是空的,所以它没有下一行。
在此代码中,在 f.createNewFile()
上放置一个断点:
File f= new File("WordDict.txt");
if(!f.exists())
try {
f.createNewFile();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
FileInputStream Fis=new FileInputStream(f);
Scanner sc = new Scanner(Fis);
System.out.println("Check outside nextline");
另一个明显的原因可能是文件存在但它是空的。
您的问题很可能是第一个问题,您的困惑来自于您对执行目录的假设。也就是说,程序很可能没有按照你想象的方式执行。要验证内容,请将 WordDict.txt
更改为绝对路径。
关于java - hasNextLine() 总是返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34453520/