gpt4 book ai didi

java - 使用二维数组时出现运行时异常

转载 作者:行者123 更新时间:2023-12-01 18:49:47 24 4
gpt4 key购买 nike

我编写了一个类,它有一个二维数组,该数组根据用户输入而增长,并允许用户在数组中输入数字。用户输入 2 2 作为尺寸,2 4 5 4 作为数字,它会像这样打印出来

2 2 
2 2

它一直有效,直到我输入数组大小 7 1 、7 行和 1 列。我遇到异常

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 为您的示例)

关于java - 使用二维数组时出现运行时异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16222519/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com