Вопрос

I'm a novice working on a homework assignment introducing us to using files in Java, and I'm trying to include an option for the user to exit early if they are not having success in creating a file (such as if they do not have permission to write to the disk). Here is the try catch block from which I'm attempting to end the program:

    // 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);
            }
        }
    }

What I think should happen is that the user will enter the term 'exit' in as the new file name and the program will exit immediately. However, when I enter in exit, the program simply creates a file called exit.txt and continues executing. I'm at a loss.

Any ideas as to what's wrong or suggestions for a better way to do this?

Это было полезно?

Решение

String are compared using equals() not != or ==.

So you need

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

See the Java tutorial for more details: http://docs.oracle.com/javase/tutorial/java/data/comparestrings.html

Btw: it's usually better to use "positive" expressions rather than negated ones (the human brain copes better with them). So it is recommended to use:

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

instead

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top