-1
import java.util.Scanner;

public class Mid {
    Scanner scan = new Scanner(System.in);
    int student;
    int arr [][]=new int[student][5];
    String str[]= {"science","math","english"};
    
    public void score() {
        System.out.println("how many student?");
        student=scan.nextInt();
        
        for(int i=0;i<student; i++) {
            for(int j=0;j<3;j++) {
                System.out.println("input"+(i+1)+"student "+str[j]+"score");
                arr[i][j]=scan.nextInt();
                }
        }
    }

I am trying to input the number of students and then the grades of the students. It keeps happening out of bounds exception... How can I solve it?

banna
  • 11
  • 4
  • 2
    You allocate an array and *then* ask the user how big the array needs to be. That needs to happen in the opposite order – Silvio Mayolo Apr 27 '21 at 03:53
  • 1
    Think about what happens if `studunt` is null then you try to use `int arr [][]=new int[student][5];`. Yes, it will be an array of 0 length. Define `student` first, or move `int arr[][]` to be after you set the value of student. – sorifiend Apr 27 '21 at 03:53

1 Answers1

1

Actually, you are not assigning any value to student before using it in the arr so the value of student by default by java will be assigned to 0.

To solve the issue you can simple take the input of "how many students?" before initializing the arr, like this:

import java.util.Scanner;

public class Mid {
    Scanner scan = new Scanner(System.in);
    int student;
    System.out.println("how many student?");
    student=scan.nextInt();
    int arr [][]=new int[student][5];
    String str[]= {"science","math","english"};

public void score() {
    
    for(int i=0;i<student; i++) {
        for(int j=0;j<3;j++) {
            System.out.println("input"+(i+1)+"student "+str[j]+"score");
            arr[i][j]=scan.nextInt();
            }
    }
}