二维数组时的运行时异常 [英] Runtime Exception while with 2d array
本文介绍了二维数组时的运行时异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了一个具有2d数组的类,该数组根据用户输入而增长,并允许用户在数组中输入数字。用户将输入 2 2
作为大小,并输入 2 4 5 4
作为数字它会像这样打印
I wrote a class that has a 2d array that grows based on user input and allows user to enter numbers in array. The user would enter 2 2
for the size and 2 4 5 4
for the numbers It would print out like this
2 2
2 2
它起作用,直到我输入一个数组大小 7 1
,7行和1列。我收到异常
It works until I enter an array size 7 1
, 7 rows and 1 column. I get an Exception
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Assignment7.main(Assignment7.java:55)
我不明白为什么
import java.util.Scanner;
public class Assignment7
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print(" ");
int [][] nums = new int[scan.nextInt()][scan.nextInt()];
System.out.print(" ");
for (int i = 0; i < nums.length; ++i)
{
for (int j = 0; j < nums.length; ++j)
{
nums[i][j] = scan.nextInt();
}
}
for (int i = 0; i < nums.length; ++i)
{
System.out.print("\n");
for (int j = 0; j < nums.length; ++j)
{
System.out.print(nums[i][j]);
}
}
}
}
推荐答案
第二维的长度应为 nums [i] .length
,注意:( i
)
second dimension's length should be nums[i].length
, Note: (i
for your example)
这篇关于二维数组时的运行时异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文