我很难找出我的代码有什么问题,在我到达锯齿数组之前,一切都很好。我希望它将代码显示为锯齿数组,但我不知道
package ajk;
public class Test2
{
public static void main(String[] args)
int[][] twoD = {
{1, 2},
{3, 4, 5},
{6},
{7, 8, 9},
};
printArray(twoD);
}
public static void printArray(int[][] arr) {
System.out.println("[");
int r = 4;
int c = 3;
int i, j;
for (i=0; i < r; i++ );
System.out.print("[");
for (j=0; j < c; j++ ) {
System.out.print( arr[i][j] + " " );
}
}
}
}发布于 2017-12-04 12:32:03
你有一些语法错误和错误:
for (i=0; i < r; i++ );You不能像这样使用for循环。你必须把你的代码写在大括号中array[i].length对于这种情况,您可以在循环的parantez内定义i和j。
如果您按如下方式更改代码:它将运行
public class Test2
{
public static void main(String[] args) {
int[][] twoD = {
{1, 2},
{3, 4, 5},
{6},
{7, 8, 9},
};
printArray(twoD);
}
public static void printArray(int[][] arr) {
System.out.println("[");
for (int i=0; i < arr.length; i++ ) {
System.out.print("[");
for (int j=0; j < arr[i].length; j++ ) {
System.out.print( arr[i][j] + " " );
}
}
}
}发布于 2017-12-04 12:38:23
你在你的代码中犯了一些错误
1.总是将for循环的代码放在花括号中,就像这样的for(){}
2.将数组索引设置为越界是一个普遍的错误,您应该使用array[i].length来确保列大小不会彼此不同
3.您的代码应该如下所示,因此请更改并尝试下面的代码
public class Test2
{
public static void main(String[] args){
int[][] twoD = {
{1, 2},
{3, 4, 5},
{6},
{7, 8, 9}
};
Test2.printArray(twoD);
}
public static void printArray(int[][] arr) {
System.out.println("[");
int r = 4;
int c = 3;
int i, j,a=0;
for(i=0; i<r; i++ ){
System.out.print("[");
for (j=0; j<arr[i].length; j++ ) {
System.out.print( arr[i][j] + " " );
}
System.out.println("]");
}
}
}和
为了更好地理解,我还添加了另一个方括号。
发布于 2017-12-04 12:50:03
实际上,这很简单。数组类有一些静态方法来打印它自己的元素(整型、双精度型、对象等)。因为这里是二维数组,所以在循环中,您将遍历arr的每个元素(这是一个int数组),并调用此方法。Arrays.toString( someArr )将someArr表示为字符串。
for (int row = 0; row < arr.length; row++) {
int[] arr1D = arr[row];
System.out.println(Arrays.toString(arr1D));
}https://stackoverflow.com/questions/47626418
复制相似问题