在java中创建一个矩阵
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36939957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
creating a matrix in java
提问by Ali12
I want to create a matrix in java .. I implemented the following code
我想在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]);
}
}
When I run the code I get the following error :
当我运行代码时,出现以下错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at shapes.Tester.main(Tester.java:8)
I tried different methods to correct the code but nothing was helpful Can you please correct the code for me ?
我尝试了不同的方法来更正代码,但没有任何帮助您能帮我更正代码吗?
thank you
谢谢你
回答by Zach Posten
When you instantiate an array, you're giving it sizes, not indices. So to use the 0th index, you need at least a size of 1.
当你实例化一个数组时,你是给它大小,而不是索引。因此,要使用第 0 个索引,您的大小至少需要为 1。
int[][] a = new int[3][1];
This will instantiate a 3x1 "matrix", meaning that valid indices for the first set of brackets are 0, 1 and 2; while the only valid index for the second set of brackets is 0. This looks like what your code requires.
这将实例化一个 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]);
}
回答by Minh Kieu
Your storing 3 elements in the first array.
您在第一个数组中存储 3 个元素。
try this int[][] a = new int[3][1];
试试这个 int[][] a = new int[3][1];