Java程序根据字符串比较不退出

标签 java while-loop try-catch system.exit

我是一名新手,正在做一项家庭作业,向我们介绍如何在 Java 中使用文件,并且我正在尝试添加一个选项,以便用户在未成功创建文件时提前退出(例如,如果他们没有写入磁盘的权限)。这是我试图从中结束程序的 try catch block :

    // Loop used to repeat try catch block until a file is successfully created/opened
    FileWriter FW = null;       // Create & initialize the FW object outside of the loop 
                                // to ensure availability in the correct scope
    boolean success = false;
    while (success == false) {
        // Try catch block for handling possible exception thrown by the 
        // FileWriter constructor
        try {
            FW = new FileWriter(fileName);
            success = true;
        } 

        // Catch allows the user to attempt to rename file and includes option
        // to exit program immediately (presumably after multiple failed attempts)
        catch (IOException e) {
            String failString = "exit";
            fileName = (String)JOptionPane.showInputDialog(
                    "There was an error creating your file.  Please\n" +
                    "ensure you have permission to write to the directory\n" +
                    "and then re-enter your desired file name.  Please do\n" +
                    "not attempt to specify a directory.  Please do not\n" +
                    "use special characters.  Type 'exit' to end the\n" +
                    "program now.");
            if (fileName != failString) {
                fileName = fileName + ".txt";
            }

            else {
                JOptionPane.showMessageDialog(null, "Exiting...", "EXITING", 1);
                System.exit(0);
            }
        }
    }

我认为应该发生的是,用户将输入术语“退出”作为新文件名,程序将立即退出。但是,当我输入 exit 时,程序只是创建一个名为 exit.txt 的文件并继续执行。我很茫然。

对于哪里出了问题有什么想法或建议更好的方法吗?

最佳答案

使用 equals() 比较字符串,而不是 !===

所以你需要

if (!fileName .equals(failstring)) {
  fileName = fileName + ".txt";
} else {
  System.exit(1);
}

有关更多详细信息,请参阅 Java 教程:http://docs.oracle.com/javase/tutorial/java/data/comparestrings.html

顺便说一句:通常使用“积极”表达比使用否定表达更好(人脑能更好地应对它们)。所以推荐使用:

if (fileName .equals(failstring)) {
  System.exit(1);
} else {
  fileName = fileName + ".txt";
}

相反

关于Java程序根据字符串比较不退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13786197/

相关文章:

c# - 即使有 while 循环,Try/catch 函数也仅运行一次 C#

c++ - 理解 try block

java - 在Catch异常之前打印出Finally

java - 使用 JPA 创建对象并将其保存到表中,但将表名称作为参数

java - gradle可以自动创建META-INF、WEB-INF文件夹和web.xml吗?

java - 是否可以根据窗口元素的时间戳动态生成 BigQuery 表名?

从资源目录读取的 Java JKS 文件 keystore 异常

python - 如果条件为 False,则重新启动循环并编辑原始列表

java - while 循环中的 Try block 在第二次迭代时不执行

java - 更改 catch block 内变量的值