我想在java中创建一个矩阵..我实现了以下代码
public class Tester {
public static void main(String[] args) {
int[][] a = new int[2][0];
a[0][0] = 3;
a[1][0] = 5;
a[2][0] = 6;
int max = 1;
for (int x = 0; x < a.length; x++) {
for (int b = 0; b < a[x].length; b++) {
if (a[x][b] > max) {
max = a[x][b];
System.out.println(max);
}
System.out.println(a[x][b]);
}
}
System.out.println(a[x][b]);
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行代码时,出现以下错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at shapes.Tester.main(Tester.java:8)
Run Code Online (Sandbox Code Playgroud)
我尝试了不同的方法来更正代码,但没有任何帮助您能帮我更正代码吗?
谢谢你
当你实例化一个数组时,你是给它大小,而不是索引。因此,要使用第 0 个索引,您的大小至少需要为 1。
int[][] a = new int[3][1];
Run Code Online (Sandbox Code Playgroud)
这将实例化一个 3x1 的“矩阵”,这意味着第一组括号的有效索引是 0、1 和 2;而第二组括号的唯一有效索引是 0。这看起来像您的代码所需要的。
public static void main(String[] args) {
// When instantiating an array, you give it sizes, not indices
int[][] arr = new int[3][1];
// These are all the valid index combinations for this array
arr[0][0] = 3;
arr[1][0] = 5;
arr[2][0] = 6;
int max = 1;
// To use these variables outside of the loop, you need to
// declare them outside the loop.
int x = 0;
int y = 0;
for (; x < arr.length; x++) {
for (; y < arr[x].length; y++) {
if (arr[x][y] > max) {
max = arr[x][y];
System.out.println(max);
}
System.out.println(arr[x][y]);
}
}
// This print statement accesses x and y outside the loop
System.out.println(arr[x][y]);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37879 次 |
| 最近记录: |