当前位置: 首页 > 知识库问答 >
问题:

我正试图创建一个程序,平均数字,但无法找出如何添加用户输入的数字在一起

史鹏云
2023-03-14

我是一名学习Java的AP计算机科学学生。我在上这门课之前学过JavaScript,但我很难弄清楚如何完成这段代码。我的老师在休假,我们的潜艇不是程序员。我很感激任何帮助。我的老师要我们写注释解释一切。下面是我的代码:

package com.company;

//导入扫描器类和任何其他需要的可导入类

public static void main(String[] args) {
    //Asks a question and lets the user input an answer, saved as the int Dividend
    System.out.println("How many numbers do you want to average?");
    Scanner dividend = new Scanner(System.in);
    int Dividend = dividend.nextInt();

    //this is a variable set in order to make the while statement work for any number
    int change = 0;

    //Asks for the numbers that should be averaged
    System.out.println("Enter the numbers to find their average: ");

    /*This is saying that while change is less than the amount of numbers being averaged,
      continue to provide an input for numbers*/
    while (change <= Dividend) {
        int Num = 0;
        int nums = 0;
        Scanner num = new Scanner(System.in);
        //I am trying to add the input to num so I can average them
        nums = num.nextInt();
        Num += nums;
        /*this is making sure that change is letting the code run through the exact amount of necessary times
          in order to input the correct amount of numbers*/
        change++;

        //once all of the numbers have been put in, average them
        if (change == Dividend) {
            System.out.println("Average: " + Num / Dividend);
        }
        System.out.println(Num);
    }


}

共有1个答案

金旺
2023-03-14

您可以使用ArrayList存储所有用户输入,然后遍历这些输入以求平均值。

 类似资料: