Java Small Coding Questions [Arrays]

Asked 2 years ago, Updated 2 years ago, 19 views

package javaprac;

import java.util.*;

public class hello {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        int num;
        double avg = 0;
        System.out.println ("Enter the number of students");
        num = scan.nextInt();

        int score[] = {0};
        for (int i = 0; i < num; i++) {
            System.out.println ("Please enter grades for student" + (i + 1) + ");
            score[i] = scan.nextInt();

            if (score[i] > 100) {
                System.out.println ("Please re-enter";

            }else {

                avg = avg + score[i];
            }
        }

        System.out.println ("Grades mean: " + avg / num);
    }
}

For coding, enter the number of students and enter the score according to the number of students Coding for averaging scores

If the number of students is set to one, the price is correct, but if there are more than two students, there is an error Please kindly tell me where the problem is. Coding no base... I'm sorry.

java

2022-09-21 16:38

2 Answers

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at javaprac.hello.main(hello.java:19)

The above exception message occurs when an invalid range is selected due to an invalid array length.

jshell> int score[] = {0};
score ==> int[1] { 0 }

If you look at the code, you have declared a single array. Because of that, when one person does it, it can be stored in the array normally, but an error occurs in the second person.

Increase the array or use ArrayList instead of array.


2022-09-21 16:38

System.out.println ("Enter the number of students");
num = scan.nextInt();

Now we have the number of students in the num variable Use this value to assign the size of the score array.

//int score[] = {0};
int score[] = new int[num]

You can edit it like this.


2022-09-21 16:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.