输入并对数字求和 - java

input and sum the numbers - java

    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行显示,这不是我想要的

使用这个:

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.

只需更换

gradeTotal = myScanner.nextDouble(); 

gradeTotal += myScanner.nextDouble();

那么平均值就是gradeTotal/i。在 while 循环外计算平均值。只有在那里变量才达到最终值。

让你远离循环。并改变这个 总成绩 = myScanner.nextDouble(); 到 总成绩 += 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();
        }

}