gpt4 book ai didi

java - 错误消息 Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException :

转载 作者:行者123 更新时间:2023-11-29 05:52:45 25 4
gpt4 key购买 nike

我有此代码,但我不断收到此错误消息,我不知道为什么?

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at javaapplication28.JavaApplication28.main(JavaApplication28.java:38) 1 2 Java Result: 1

public static void main(String[] args) {   

Scanner input = new Scanner(System.in);
System.out.println("This program transposes a matrix.");
System.out.println("Please enter the number of rows");
int rows = input.nextInt();
System.out.println("User enters: "+rows);
System.out.println("Please enter the number of columns");
int columns = input.nextInt();
System.out.println("User enters: "+columns);
int [][]matrix=new int[rows][columns];
for(int i=0;i<matrix.length;i++){
for(int j=0;j<matrix[i].length;j++){
System.out.print("Enter value for row [" +i+ "] column [" +j+"]:");
matrix[i][j]=input.nextInt();
}
}
for(int i=0;i<=matrix.length;i++){
System.out.println();
for(int j=0;j<=matrix.length;j++){
System.out.print(matrix[i][j]+" ");
}
}
System.out.println("The transpose of this matrix has" +columns+"rows and"+rows+"columns and the transpose is:");
for(int i=0;i<=matrix.length;i++){
System.out.println();
for(int j=0;j<=matrix.length;j++){
System.out.print(matrix[j][i]+" ");
}
}}
}

最佳答案

你在从 0 到 length+1 的循环中运行 i<=matrix.length .删除 =来自 for语句和内部循环添加:matrix[i].length相反 matrix.length获取列数而不是行数。

这里是有效代码:

for(int i=0;i<matrix.length;i++){
System.out.println();
for(int j=0;j<matrix[i].length;j++){
System.out.print(matrix[i][j]+" ");
}
}
System.out.println("The transpose of this matrix has" +columns+"rows and"+rows+"columns and the transpose is:");
for(int i=0;i<matrix.length;i++){
System.out.println();
for(int j=0;j<matrix[i].length;j++){
System.out.print(matrix[j][i]+" ");
}
}}

关于java - 错误消息 Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13296816/

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