[英]Why can I create a two dimensional array with 0 rows but 5 columns in java?
[英]How can I create a simple 4x3 two dimensional array in Java?
我已经用C ++了解它,但Java对我来说更具挑战性。 这就是我所拥有的。 我只想让它有4行3列初始化为1-12并将其打印到屏幕上。 我的错误对你来说是否明显? 谢谢!
我得到13个错误:(
包括line9:twoDArray [] []不是声明,; 预期的,非法的表达开始,每次都是几次。
我试过的代码:
import java.util.*;
class twoDimensional array
{ public static void main(String args[])
{
int[][] twoDArray = new int[4][3];
twoDArray[][]={{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
System.out.print(twoDArray.toString);
}
}
首先,数组(甚至是2d数组)不会覆盖Object.toString
。 您可以使用Arrays.deepToString(Object[])
并在声明时初始化数组。 就像是
int[][] twoDArray = new int[][] {
{ 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 }
};
System.out.println(Arrays.deepToString(twoDArray));
修改了你的代码
import java.util.*;
class twoDimensional array
{
public static void main(String args[]){
int[][] twoDArray = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
//For printing array you have to do
System.out.print(Arrays.deepToString(twoDArray));
}
}
import java.util.*;
class twoDimensionalArray
{
public static void main(String args[])
{
int[][] twoDArray = new int[][] {
{ 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 }
};
System.out.println(Arrays.deepToString(twoDArray));
}
}
这是完整的工作副本
public class TwoD {
public static void main(String... args)
{
int [][]twoD = new int[4][3];
int num = 1;
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 3; j++)
{
twoD[i][j] = num;
num++;
}
}
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.print(twoD[i][j]+"\t");
}
System.out.println("");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.