Java if语句和写行

Java if statements and write lines

我正在尝试让我的 if 语句具有单独的写入命令,例如 bw.write(b + " - " + a +" = " + c + newLine); 这个问题是由于 newLine 字符串和 bw 缓冲区在 curley 括号内,我无法让它们工作。有什么想法吗?

try {                       
    File file = new File("src/written.txt"); 
    if (!file.exists()) {
        file.createNewFile();
    }
    FileWriter fw = new FileWriter(file, true);
    BufferedWriter bw = new BufferedWriter(fw);
    String newLine = System.getProperty("line.separator");
    bw.write(b + " - " + a +" = " + c + newLine);
    bw.close();
} catch (IOException e) {
    e.printStackTrace();
}

JOptionPane.showMessageDialog(null,"Amount Transfered: " + b + " - " + "Previous Balance: " + a +"\nRemaning Balance: " + c);

if( c == 0){
    JOptionPane.showMessageDialog(null,"Transfered granted. Balance empty","Transation successful!",JOptionPane.WARNING_MESSAGE);
}else if (c > 0){
    JOptionPane.showMessageDialog(null,"Transfered granted.","Transation successful!",JOptionPane.INFORMATION_MESSAGE);
}else{
    JOptionPane.showMessageDialog(null,"Transfer denied due to insufficent funds.","Transaction denied!",JOptionPane.ERROR_MESSAGE);
}

我不完全确定你的目标是什么,但看起来你正在失去 BufferedWriter bw 的范围。

如果您想在当前所在的 { } 之外使用 bw,请声明:

BufferedWriter bw;
try {
.....
bw = new BufferedWriter(fw);
}

这样,bw 在 try 块之前声明,这样您就可以在代码的其余部分以及 try 块中使用它。