gpt4 book ai didi

java - 每当我的列大于我的行时,就会出现越界异常

转载 作者:行者123 更新时间:2023-12-02 05:00:39 24 4
gpt4 key购买 nike

我一直在用我的代码把头撞在墙上。我终于得到了我的代码,允许我输入用户想要的任何数字,具体取决于他们想要的行数和列数,但由于某种原因,每当我尝试输入比行号更大的列号时,我都会收到错误。我已经阅读了我的循环数十次,在我认为程序过度计数的地方插入-1,但它仍然无法工作。我假设这是编写完全依赖于用户的多维数组的适当方法,但如果不是,请告诉我如何使我的代码更高效。谢谢!

public class MultiPractice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

// Prompts user to insert desired rows and columns
System.out.print("Enter how many rows you want in your array: ");
int rowSize = input.nextInt();
System.out.print("Enter hwo many columns you want in your array: ");
int colSize = input.nextInt();

// Asks users to insert desired numbers for the multi-array
System.out.print("Enter " + (rowSize*colSize) + " integers: ");

// Creates the multidimensional array
int[][] multi = new int[rowSize][colSize];

// Runs the for loop to put numbers where they belong in array
for (int i = 0; i < multi.length; i++) {
for (int j = 0; j < multi[colSize].length; j++) {
multi[i][j] = input.nextInt();
System.out.print(multi[i][j] + " ");
}
System.out.println();
}

}
}

最佳答案

multi[colSize].length 应该是 multi[0].lengthmulti[i].length (因为你有一个矩形数组,它们具有相同的值)。

multi[colSize].length 是行 colSize 的长度。因此,如果您的行数少于 colSize+1 行(因为它们从 0 开始),则这是越界的。

关于java - 每当我的列大于我的行时,就会出现越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28311150/

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