【发布时间】:2016-07-06 16:11:55
【问题描述】:
为什么我的 if-else 块没有检测到 gamma 为空?这是我的代码。它是一个电子表格应用程序,这是一个保存函数,它遍历表中的所有单元格并将其写入文件。这是我的代码:
public void Save () {
String FileName = JOptionPane.showInputDialog("Please enter the name for your file:");
if (FileName == null) {
System.err.println("You didn't enter anything");
} else {
int rows = Table.getRowCount();
int columns = Table.getColumnCount();
int alpha = 0;
int beta = 1;
choicer.setCurrentDirectory(new java.io.File("Desktop"));
choicer.setDialogTitle("Save Document");
choicer.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
choicer.setAcceptAllFileFilterUsed(false);
if (choicer.showSaveDialog(new JPanel()) == JFileChooser.APPROVE_OPTION) {
dir = String.valueOf(choicer.getSelectedFile());
}
File f = new File(dir + "\\" + FileName + ".txt");
try {
fos = new FileOutputStream(f);
osw = new OutputStreamWriter(fos);
w = new BufferedWriter(osw);
for (alpha = 0; alpha <= rows - 1; alpha++) {
for (beta = 1; beta < columns; beta++) {
String gamma = String.valueOf(Table.getValueAt(alpha, beta));
if (gamma != null) {
w.write("<%! " + gamma + " !%> ");
} else {
w.write(" <%! |^-^| !%> ");
}
}
w.write("\n");
}
} catch (IOException e) {
System.err.println("Some prob dude. Too big for me");
} finally {
try {
w.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
我尝试了重复的东西给出的链接,但这并没有解决我的问题。如果我这样做if(gamma != null && !(gamma.isEmpty)),那么只有 null 作为 gamma 的值写入文件。
【问题讨论】:
-
也许,gamma 不是空的……而是空的,不是吗?检查如下:“gamma != null && !gamma.isEmpty()”
-
也许您可以将代码示例减少到显着的行,并包含详细信息。 Table.getValueAt() ?
-
@BrianAgnew 我添加了所有代码以防万一有人需要额外的验证
-
@GuilhermeP 如果我这样做 if( gamma != "") 它会写 null
-
@RahulSrinath 这是因为在您调用
String.valueOf之前的行上的变量值为null。gamma在这种情况下不是null,而是变成了字符串"null"。