尝试将值输入到2d数组并打印,代码未运行

时间:2017-04-21 22:24:30

标签: java

代码没有运行?

import java.util.Scanner;
public class Array2dNightPractice
{
    int[][] studentmarks;
    studentmarks = new int[3][3];

    Scanner kb = new Scanner(System.in);
    System.out.println("Enter 9 integers");

    for(int row = 0;row<3;row++){
        for(int col=0;col<3;col++){
            studentmarks[row][col] = kb.nextInt();
        }
    }

    for(int row = 0; row < 3; row++) {
        for(int col = 0; col < 4; col++) {
            System.out.print(studentmarks[row][col] + " ");
        }
        System.out.println();
    }
}

2 个答案:

答案 0 :(得分:0)

你因此而得到IndexOutOfBoundsException - &gt; col < 4

for(int col = 0; col < 4; col++)

改为:

for(int col = 0; col < studentmarks[row].length; col++)

旁注 - 使用length属性来防止您刚遇到的错误等错误。

完整解决方案:

for(int row = 0; row < studentmarks.length; row++) {
     for(int col = 0; col < studentmarks[row].length; col++) {
         System.out.print(studentmarks[row][col] + " ");
     }
     System.out.println();
}

答案 1 :(得分:0)

错误来自超出数字studentMarks的第二个for循环中数组4的界限,它应该是3 开发的一个好习惯是根据需要创建每个行和列的大小的常量变量,这样你就不会陷入这样的错误。 像这样:

import java.util.Scanner;
public class Array2dNightPractice{
  public static void main(String[] agrs){
    final int ROW =3, COL=3; // constant variable to determine the size of the 2d array
    int[][] studentMarks = new int[ROW][COL];
    Scanner in = new Scanner(System.in);
    System.out.println("Enter 9 integers");
    for(int row = 0;row<ROW;row++){ //note how I don't need to memorize and rewrite the numbers every time
        for(int col=0;col<COL;col++){
            studentMarks[row][col] = in.nextInt(); 
        }
    }
    // print the marks as matrix
    for(int row =0; row <ROW; row++) {   
        for(int col =0; col <COL; col++) {  
            System.out.print(studentMarks[row][col] + " "); 
        }
        System.out.println();
    }
  }
}