输入并汇总数字 - java

时间:2015-03-21 19:26:51

标签: java file-io

    import java.util.Scanner; //Needed for the scanner class
    import java.io.File; //Needed for the file class
    import java.io.IOException; //Needed for the IOException

    public class AverageGrade {

        public static void main(String[] args) throws IOException {
            int i = 0;
            double sum = 0.0;
            double gradeTotal =  0.0;

            // Open the file

            File myFile = new File("C:\\Users\\life__000\\Desktop\\Eclipse - Java\\AverageGrade\\src\\myGrades.txt");
            Scanner myScanner = new Scanner(myFile);

            //Read lines from the file until no more are left.
            while (myScanner.hasNextDouble()) {
                //Read the next name
                gradeTotal = myScanner.nextDouble();

                i++;

                //Display the last name read.
                System.out.println(gradeTotal);
            }

            // Close the file.
            myScanner.close();
        }

这是我的代码。它读取文件输入但它没有添加它们。我想添加数字,然后取其平均值。我已经试过了 gradeTotal += myScanner.nextDouble(); 但使用上面的行打印所有数字而不是添加3个数字。

txt文件中的3个数字在一行中为95.0 90.0 80.0。输入后,它们会显示在3条不同的行上,这不是我想要的。

3 个答案:

答案 0 :(得分:1)

使用此:

gradeTotal =gradeTotal+ myScanner.nextDouble();
//this adds the value from the file to the value in the variable

你在做:

gradeTotal = myScanner.nextDouble();
//this just overwrites the value already in the variable.

答案 1 :(得分:0)

只需替换

gradeTotal = myScanner.nextDouble(); 

gradeTotal += myScanner.nextDouble();

然后平均值为gradeTotal / i。计算while循环外的平均值。只有变量已达到最终值。

答案 2 :(得分:0)

让你在循环边跳出来。并改变这一点 gradeTotal = myScanner.nextDouble(); 至 gradeTotal + = myScanner.nextDouble();

public class AverageGrade {




        public static void main(String[] args) throws IOException


    {       
            int i = 0;
            double sum = 0.0;
            double gradeTotal =  0.0;

            // Open the file

            File myFile = new File("C:\\Users\\life__000\\Desktop\\Eclipse - Java\\AverageGrade\\src\\myGrades.txt");
            Scanner myScanner = new Scanner(myFile);

            //Read lines from the file until no more are left.

            while (myScanner.hasNextDouble())

            {
                //Read the next name

                gradeTotal += myScanner.nextDouble();

                i++;

                //Display the last name read.




            }

            // Close the file.
  System.out.println(gradeTotal);
            myScanner.close();
        }

}