我是一名新手从事家庭作业,介绍我们使用Java中的文件,我试图为用户提供一个选项,如果他们没有成功创建文件(例如if)他们没有权限写入磁盘)。这是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'作为新文件名,程序将立即退出。但是,当我进入exit时,程序只是创建一个名为exit.txt的文件并继续执行。我很茫然。
关于什么是错的任何想法或建议更好的方法吗?
答案 0 :(得分:2)
使用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";
}
代替