我正在尝试检查用户给出的单词是否已存在于文本文件中或它的子字符串是否已存在。这是我的代码:
String ans = null;
Scanner scanner = null;
do
{
System.out.print("Please enter a new word: ");
String Nword = scan.next();
System.out.print("And its appropriate Hint: ");
String Nhint = scan.next();
Word word = new Word(Nword , Nhint);
File file = new File("C:\\Users\\Charbel\\Desktop\\Dictionary.txt");
file.createNewFile();
scanner = new Scanner(file);
if (scanner != null)
{
String line;
while (scanner.hasNext()) {
line = scanner.next();
for(int i = 0 ; i<line.length(); i++)
if ((line.equals(Nword)) || (Nword.equals(line.substring(i))))
{
System.out.println("The word already exists.");
break;
}
}
}
else
{
FileWriter writer = new FileWriter(file , true);
writer.write(word.toString());
writer.write(System.lineSeparator());
writer.flush();
writer.close();
System.out.println("Your word has successfuly added.");
System.out.print("\nWould you like to add another word ?\nPress 0 to continue.");
ans = scan.next();
}
} while(ans.equals("0"));
Eclipse 说 else
条件之后的语句是“死代码”,我不知道为什么。
最佳答案
scanner = new Scanner(file);
scanner
已初始化,永远不能为 null
,因此永远不会到达 else
语句。
参见 constructor :
Throws:
FileNotFoundException
- if source is not found
因此,如果 file
不存在,scanner
将不会是 null
,您将遇到一个异常.
关于java - 死代码java eclipse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20786999/