Anmol Bhullar
Anmol Bhullar

Reputation: 145

Getting weird outputs when I try to print my multidimensional array

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

}

Upvotes: 0

Views: 169

Answers (4)

Java Devil
Java Devil

Reputation: 10959

To print on the same line you will not be able to use the println() method each time in your inner loop, either create a string for each object in the inner loop and then put println in the outer loop or use print() in the inner loop then print a new line in the outer loop.

Like

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

Upvotes: 1

jh314
jh314

Reputation: 27792

In your for loop, you simply print objectList[1][1], which you never initialized, so it is null. You loop 3 * 4 = 12 times, so you get 12 null's. If you print objectList[i][j], you will get the contents of the array.

Upvotes: 0

james
james

Reputation: 26271

Use variables while printing the array instead of [1][1] try [i][j]

Upvotes: 0

Jeff
Jeff

Reputation: 12785

You're printing [1][1] instead of [i][j].

Try:

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

Oh yeah, and you initialize [0][1] instead of [1][1]. Try:

objectList[1][0] = "Teapot";
objectList[1][1] = String.valueOf(2);

Upvotes: 1

Related Questions