[英]Dead code java eclipse
我正在尝试检查用户给定的单词在文本文件中是否已经存在或它的子字符串是否已经存在。 这是我的代码:
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
语句。
参见构造函数 :
抛出:
FileNotFoundException
如果找不到源
因此,如果file
不存在, scanner
将不会为null
,那么您将有一个异常 。
scanner = new Scanner(file);
该语句在这里创建一个新实例。 所以这就是: if (scanner != null)
永远不会为假。
Dead-Code
永远不会执行,例如:
if(true) {
// do something
}else {
// do something else <-- this is dead code, or else-block is dead code
}
在您的情况下,由于Scanner
是在if(scanner != null)
之前创建的,因此无法执行关联else
。 如果Scanner
创建失败错误将被再次抛出在else
不会被执行,因此,从编译器的点的视图没有机会else
块得到执行,因此dead-code
。
if-else
将scanner
实例作为参数传递, if-else
会有意义。
要解决此问题, else
应删除!
以下应纠正您的代码:
scanner = new Scanner(file);
FileWriter writer = new FileWriter(file, true);
if (scanner != null) {
String line;
while (scanner.hasNext()) {
line = scanner.next();
for (int i = 0; i < line.length(); i++)
if ((line.equals(""))
|| ("".equals(line.substring(i)))) {
System.out.println("The word already exists.");
break;
} else {
writer.write(word.toString());
writer.write(System.lineSeparator());
writer.flush();
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();
}
}
}
writer.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.