【问题标题】:Java program does not exit based on string comparisonJava程序不基于字符串比较退出
【发布时间】:2012-12-09 09:22:15
【问题描述】:

我是一名新手,正在做一项家庭作业,向我们介绍如何在 Java 中使用文件,我正在尝试为用户提供一个选项,如果他们没有成功创建文件(例如,如果他们没有写入磁盘的权限)。这是我试图结束程序的 try catch 块:

    // 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.txt 的文件并继续执行。我很茫然。

关于什么是错误的任何想法或更好的方法的建议?

【问题讨论】:

  • 你应该使用 filename.equals(failstring) - Strings 是对象,所以使用 ==!= 不能充分比较它们

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


【解决方案1】:

使用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";
}

改为

【讨论】:

  • 太棒了!效果很好!感谢您的提示和教程!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-11
  • 2012-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多