通过数组传递不确定量的Int

时间:2018-07-09 23:50:47

标签: java arrays

我在Java编程入门课程中,我试图弄清楚如何从用户输入的Int填充数组。我已经看过我教授的所有视频,并做了很多谷歌搜索,但是我还没弄清楚。

import java.util.Scanner;

public class GradesForClass {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);

        System.out.println("Hello Drews, how many total grades do you want to process?");
        int numberOfGrades = keyboard.nextInt();

        int sum = 0;

        for (int i = 0; i < numberOfGrades; i++) {
            System.out.println("Please enter grade " + (i + 1) + ": ");
            int userGradeNumbers = keyboard.nextInt();
            sum += userGradeNumbers;            
        }

        int storeGrades[] = new int[userGradeNumbers];

        int totalScore = sum;
        //int lowestScore = ;
        //int highestScore = ;
        double averageScore = sum / (double) numberOfGrades;

        System.out.println("Total score is: " + totalScore);
        //System.out.println("Lowest score is: " + lowestScore);
        //System.out.println("Highest score is: " + highestScore);
        System.out.println("Average score is: " + averageScore);

        keyboard.close();
    }
}

2 个答案:

答案 0 :(得分:1)

由于您知道要处理多少个成绩,所以最简单的方法是在开始向用户要求输入之前在之前创建一个数组。

int[] storeGrades = new int[numberOfGrades];

代替当前输入的

一旦有了,就可以使用0到numberOfGrades - 1之间的数字引用数组的元素。特别是,在输入数字的循环中

storeGrades[i] = userGradeNumbers;

因为i是一个精确遍历您所需范围的索引。

答案 1 :(得分:0)

代替此操作(创建一个没有分数的storeGrades数组):

    int sum = 0;

    for (int i = 0; i < numberOfGrades; i++) {
        System.out.println("Please enter grade " + (i + 1) + ": ");
        int userGradeNumbers = keyboard.nextInt();
        sum += userGradeNumbers;            
    } 

    int storeGrades[] = new int[userGradeNumbers];

执行此操作:

    int storeGrades[] = new int[numberOfGrades];
    int sum = 0;

    for (int i = 0; i < numberOfGrades; i++) {
        System.out.println("Please enter grade " + (i + 1) + ": ");
        int grade = keyboard.nextInt();
        storeGrades[i] = grade;
        sum += grade;            
    }

在上述for循环之后,storeGrades将包含各个成绩。