java - 死代码java eclipse

标签 java dead-code

我正在尝试检查用户给出的单词是否已存在于文本文件中或它的子字符串是否已存在。这是我的代码:

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/

相关文章:

java - 更新结果集后更新数据库

java - 在 Eclipse 中,您如何找到已定义但未在应用程序中的任何地方使用/调用的方法?

java - 如何在 Java 项目中查找未使用/死代码

更改 C 代码以完全运行(包括 if 的所有部分)

grails - 相当于Groovy/Grails的UCD吗?

c - 什么是AST、CFG、CLANG,我们如何在deadcode去除算法中使用它们?

java - 使用 JGit 创建一个从属性克隆存储库的工具

java - 在 eclipse 中按实现类搜索

java - dispatchKeyEvent 调用方法两次

java - 在 Android 日期选择器中将最大日期设置为 30 天