我如何使用二维数组

时间:2015-11-30 02:28:02

标签: java arrays

我构建(差)一个二维数组来保存学生姓名和成绩。它确实提示我学生的名字等于我想要的数量,但它不适用于成绩。它还声明我有一个超出范围的索引,我不知道这是怎么发生的。

private void studentArray() {
            int rows = 0;
            int col = 0;

            Scanner input = new Scanner(System.in);

            System.out.println("How many students do you have?");
            rows = input.nextInt();

            System.out.println("How many tests would you like to record?");
            col = input.nextInt();

           String [][] schoolArray =  new String[rows][col];

           for (int row = 0; row < rows; row++ ){
            System.out.println("Please enter student name.");
            schoolArray[row][0] = input.next();
                for(int cols = 1; cols < col; cols++){
                System.out.println("Please enter grades.");
                schoolArray[cols][0] = input.next();
                }//end of col for loop
        }//end of row for loop
           printSchool (schoolArray, rows, col);


        }//end of studentArray

        private void printSchool(String[][]schoolArray, int rows, int col){
            for ( int row = 0; row < schoolArray.length; row ++) {
                System.out.print(schoolArray[rows][col + 1] + "\t");
            }
        }

2 个答案:

答案 0 :(得分:0)

我认为你错误地写了这个body .modal-dialog { margin-left: 0 } 它应该是school[cols][0]里面的col for loop

答案 1 :(得分:0)

首次使用 -

schoolArray[row][cols] = input.next(); 

而不是

schoolArray[cols][0] = input.next(); 

并且还更改了printSchool方法 -

 private void printSchool(String[][]schoolArray, int rows, int col){
                for ( int row = 0; row < rows; row ++) {
                       System.out.print("\n");
                       for(int cols= 0; cols < col ;cols++){

                    System.out.print(schoolArray[row][cols] + "\t");
                  }
                }
            }