Java增加TXT文件的总量

时间:2015-05-18 04:33:19

标签: java double

尝试以总金额显示余额金额时,文本文件的格式如下:

12
-10.20
5.00

以及此代码循环如下所示,这个I的主要部分试图获得总余额。和它的返回值,但似乎打印出0.00,

public static double BalanceCheck(String FileName, String Returned) {
    try {
        ArrayList<String> Trains = new ArrayList<String>();         
        int count = 0;
        double Balance = 0;
        File file = new File(FileName);
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        StringBuffer stringBuffer = new StringBuffer();
        String line;
        while ((line = bufferedReader.readLine()) != null) 
        {


                if(line.startsWith("-")){
                    String templine = line.replace("-", "");
                    Balance = Double.parseDouble(templine);
                    Balance -=  Balance;
                }
                else{
                    String tempBalance = line;
                    Balance = Double.parseDouble(tempBalance);
                    Balance += Balance;
                }
                System.out.println(Balance);


        }
    Balance = Double.parseDouble(new DecimalFormat("##.####").format(Balance));
    return Balance;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return (Double) null;
    }

1 个答案:

答案 0 :(得分:1)

这里有一些应该做好事的代码。请注意我在原帖中的评论中突出显示的问题。

public static double getBalance(String fileName) {
    double balance = 0.0;
    Scanner scanner = null;
    try {
        scanner = new Scanner(new File(fileName));
        while (scanner.hasNextDouble()) {
            balance += scanner.nextDouble();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
    return balance;
}