当我尝试打印该程序时,它在所有新行中都输出null 12次,所以有人可以告诉我我做错了什么吗?
我希望该程序在一行中打印对象及其权重,然后在另一行中打印下一个对象及其权重,依此类推...
public class ojArray {
public static void main(String[] args) {
//makes a new multidimensial array
//the first dimension holds the name of the object
//the second dimension holds the weight
//the 4's in this case show the maximum space the array can hold
String[][] objectList = new String[4][4];
objectList[1][0] = "Teapot";
objectList[0][1] = String.valueOf(2);
objectList[2][0] = "Chesterfield";
objectList[2][2] = String.valueOf(120);
objectList[3][0] = "Laptop";
objectList[3][3] = String.valueOf(6);
//printing the array
for (int i = 1; i < objectList.length; i++) {
for (int j = 0; j < objectList.length; j++) {
int k = 1;
System.out.println(objectList[1][1]);
}
}
}
}
最佳答案
您正在打印[1][1]
而不是[i][j]
。
尝试:
for (int i = 1; i < objectList.length; i++) {
for (int j = 0; j < objectList.length; j++) {
int k = 1;
System.out.println(objectList[i][j]);
}
}
哦,是的,您初始化了
[0][1]
而不是[1][1]
。尝试:objectList[1][0] = "Teapot";
objectList[1][1] = String.valueOf(2);