0

When I try to print this program it outputs null 12 times all in new line, so can someone tell me what I am doing wrong?

I want this program to print the object and its weight in one line and then print the next object and its weight in another line and so on...

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]);
        }
    }
}

}

4

4 回答 4

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);
于 2013-06-24T01:24:03.067 回答
1

要在同一行上打印,您将无法println()在内部循环中每次都使用该方法,要么为内部循环中的每个对象创建一个字符串,然后将 println 放在外部循环中,要么print()在内部循环中使用,然后打印一个外循环中的新行。

喜欢

for (int i = 1; i < objectList.length; i++) 
{
        String output = "";
        for (int j = 0; j < objectList.length; j++) 
        {
            int k = 1;
            output += objectList[i][j] + " ";
        }
        println(output);
}
于 2013-06-24T01:27:12.373 回答
0

在打印数组时使用变量而不是[1][1]尝试[i][j]

于 2013-06-24T01:24:24.943 回答
0

在您的 for 循环中,您只需 print objectList[1][1],您从未初始化过它,因此它为空。你循环 3 * 4 = 12 次,所以你得到 12 个空值。如果你 print objectList[i][j],你会得到数组的内容。

于 2013-06-24T01:24:27.440 回答