2017-04-21 148 views
-2

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

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(); 
    } 
} 
+1

什么是错误?请详细说明你的问题。 – rotgers

+1

这个for(int col = 0; col <4; col ++)'可能会给你一个错误,因为只有3个索引。没有'studentmarks [3] [4]'。它显然应该是for(int col = 0; col <3; col ++)'。 – rotgers

+0

你应该看到索引超出范围错误?你看到了吗? –

回答

0

你得到IndexOutOfBoundsException因为这个 - >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(); 
} 
0

错误来自于第二个在数字4超过绑定的阵列studentMarks的for循环应该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(); 
    } 
    } 
} 
相关问题