簡體   English   中英

在文本文件中添加雙打的代碼? Java的

[英]Code for adding doubles within a text file? Java

我想知道以下代碼是否在文本文件中返回所有雙精度值的總和。 當我測試運行它時,它似乎總是顯示為0.0。 可能是什么問題呢? 一世

public double honorsCalculation() throws IOException {
    Scanner test = new Scanner(new File("Calculus - Test.txt"));
    while (test.hasNext()) {
        ArrayList <Double> assignments = new ArrayList <Double> ();
        double num = test.nextDouble();
        assignments.add(num);
        for (int i = 1; i < assignments.size() - 1; i++) {
            sum = sum + assignments.get(i);
            percentage = sum;
        }
    }
    return percentage;
}

您根本不需要ArrayList ,很難看到一個百分比如何等於總和,或者在哪里初始化變量:

public double honorsCalculation() throws IOException {
    double sum = 0;
    Scanner test = new Scanner(new File("Calculus - Test.txt"));
    while (test.hasNext()) {
        sum += test.nextDouble();
    }
    return sum;
}

您在讀取所有數據之前正在處理信息。

public double honorsCalculation() throws IOException {
    Scanner test = new Scanner(new File("Calculus - Test.txt"));
    ArrayList <Double> assignments = new ArrayList <Double> ();
    while (test.hasNext()) {
        double num = test.nextDouble();
        assignments.add(num);
    }
    for (int i = 1; i < assignments.size() - 1; i++) {
        sum = sum + assignments.get(i);
        percentage = sum;
    }
    return percentage;
}

這應該是正確的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM