简体   繁体   English

Java if语句和写行

[英]Java if statements and write lines

I am trying to get my if statements to have seperate write commands such as bw.write(b + " - " + a +" = " + c + newLine); 我试图让我的if语句具有单独的写命令,例如bw.write(b + " - " + a +" = " + c + newLine); the issue is due to the newLine string and the bw Buffer being within curley braces I cannot get those to work. 问题是由于newLine字符串和bw Buffer位于大括号内,我无法使其正常工作。 any ideas? 有任何想法吗?

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

I'm not entirely sure what your goal is, but it looks like you're losing the scope on your BufferedWriter bw. 我不能完全确定您的目标是什么,但看起来您正在丢失BufferedWriter bw的作用域。

If you want to use bw outside the { } it currently resides in, declare: 如果要在当前驻留的{}之外使用bw,请声明:

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

That way, bw is declared before the try block, which lets you use it all throughout the rest of the code as well as within the try block. 这样,bw会在try块之前声明,这样您就可以在代码的其余部分以及try块中使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM