如何正确提示用户输入以下数组的大小?

问题描述 投票:0回答:1

我无法将数字numberofStudents存储到以下数组中。 int[] arr可以正常工作,但其余部分则不能。

错误消息:线程“ main”中的异常java.lang.ArrayIndexOutOfBoundsException:2

我在做什么错?

    System.out.print("Enter the number of students you would like to compute: ");
        int numberOfStudents = input.nextInt(); 
        int[] arr = new int[numberOfStudents];
        int[] classNumber = new int[numberOfStudents];
        int[] age = new int[numberOfStudents];
        double[] mathematics = new double[numberOfStudents];
        double[] grammar = new double[numberOfStudents];
        double[] socialStudies = new double[numberOfStudents];
        double[] science = new double[numberOfStudents];
        double[] creativeWriting = new double[numberOfStudents];
        double[] sum = new double[numberOfStudents];
        String[] firstName = new String[numberOfStudents];
        String[] lastName = new String[numberOfStudents];
        String[] gender = new String[numberOfStudents];
for (int i = 0; i < arr.length; i++) {
            System.out.println("");
            System.out.println("--------- STUDENT #" + (i + 1) + " ---------"); 
            System.out.print("First name: ");
            firstName[i] = input.next();
            System.out.print("Last name: ");
            lastName[i] = input.next();
            System.out.print("Gender: ");
            gender[i] = input.next();
            System.out.print("Age: ");
            age[i] = input.nextInt();
            System.out.print("Classroom #: ");
            classNumber[i] = input.nextInt();
            System.out.println("**Please enter marks made out of 100!");
            System.out.print("Mathematics: ");
            mathematics[i] = input.nextDouble();
            System.out.print("Grammar: ");
            grammar[i] = input.nextDouble();
            System.out.print("Social Studies: ");
            socialStudies[i] = input.nextDouble();
            System.out.print("Science: ");
            science[i] = input.nextDouble();
            System.out.print("Creative Writing: ");
            creativeWriting[i] = input.nextDouble();
            sum[i] = (mathematics[i] + grammar[i] + socialStudies[i] + science[i] + creativeWriting[i]);
            System.out.println("");
        }

java arrays size
1个回答
0
投票

您使用的数组不正确。

int n = 5;

这表示数组numbers的大小为5。

int [] numbers = new int[n]; 

所以您可以这样填充它。

for (int i = 0; i < n; i++) {
    numbers[i] = i * 10;
}

for (int i = 0; i < n; i++) {
   System.out.println(numbers[i]);
}



© www.soinside.com 2019 - 2024. All rights reserved.