[英]Runtime Exception while with 2d array
I wrote a class that has a 2d array that grows based on user input and allows user to enter numbers in array. 我编写了一个具有2d数组的类,该数组根据用户输入而增长,并允许用户在数组中输入数字。 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
2 4 5 4
作为数字。它将像这样打印出来
2 2
2 2
It works until I enter an array size 7 1
, 7 rows and 1 column. 直到我输入一个数组大小
7 1
1,7行和1列,它才起作用。 I get an Exception 我得到一个例外
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Assignment7.main(Assignment7.java:55)
I don't understand why 我不明白为什么
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
)
For your inner loop, you're using the size of the outer array: 对于内部循环,您正在使用外部数组的大小:
for (int i = 0; i < nums.length; ++i)
{
for (int j = 0; j < nums.length; ++j)
This should be: 应该是:
for (int i = 0; i < nums.length; ++i)
{
for (int j = 0; j < nums[i].length; ++j)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.