I want to know how to declare a Java array

Asked 2 years ago, Updated 2 years ago, 48 views

Code that declares a ragged array (gradeHeights) and then enters a value into the array (setData).

int[][] gradeHeights = new int[5][]; is fine, but specifying the length of the two-dimensional array below it continues to cause problems.

import java.util.Scanner;

public class ManagerHeight {
    Scanner scan = new Scanner(System.in);

    public static void main(String[] args){
        ManagerHeight manager = new ManagerHeight();
        manager.setData(manager.gradeHeights);
    }
    int[][] gradeHeights = new int[5][];

    gradeHeights[0] = new int[5];
    gradeHeights[1] = new int[4];
    gradeHeights[2] = new int[4];
    gradeHeights[3] = new int[3];
    gradeHeights[4] = new int[5];

    public void setData(int[][] clss){
        for(int i=0; i<4; i++){
            for(int k=0; k<gradeHeights[i].length; k++){
                System.out.println(1+i+"Class"+(1+k)+"What is the height of the student?");
                clss[i][k] = scan.nextInt();
            }
        }
    }
}

java

2022-09-22 21:34

1 Answers

gradeHeights[0] = new int[5];
gradeHeights[1] = new int[4];
gradeHeights[2] = new int[4];
gradeHeights[3] = new int[3];
gradeHeights[4] = new int[5];

Try putting this part in the setData method. It is impossible to access the object assigned as new from the outside of the method.


2022-09-22 21:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.