badweight
badweight

Reputation: 11

Issues with my simple 2D array

So I'm trying to make a basic 2d array with rows and columns in Java using netbeans 8.1.

This is my code:

public static void main(String[]args)
{
    int temp = 5;
    int temp2 = 10;

    for(int i = 0; i < temp2; ++i)
    {
        for(int k = 0; k < temp; ++k)
        {
            System.out.println("|_|");
        }
        System.out.println("\n");
    }
}

But for some reason, the output looks like this:

output

Could someone help me understand what is wrong?

Upvotes: 1

Views: 51

Answers (2)

Jeremy Grand
Jeremy Grand

Reputation: 2370

I found dat3450's answer to be enough to resolve your issue, but the System.out.println(""); irked me a little bit. So, that's how I'd do it :

public static void main(String[] args) {
    int temp = 5;
    int temp2 = 10;

    for(int i = 0; i < temp2; ++i)
    {
        StringBuilder row = new StringBuilder();
        for(int k = 0; k < temp; ++k)
        {
            row.append("|_|");  //concat the cells in the same String
        }
        System.out.println(row.toString()); //prints one entire row at a time
    }
}

Upvotes: 0

dat3450
dat3450

Reputation: 954

It seems you should be using print in combination with println, see below:

public static void main(String[]args)
{
    int temp = 5;
    int temp2 = 10;

    for(int i = 0; i < temp2; ++i)
    {
        for(int k = 0; k < temp; ++k)
        {
            System.out.print("|_|"); //Prints each cell one after another in the same row.
        }
        System.out.println(""); //Prints a new row, .println("\n") will print two new rows.
    }
}

Upvotes: 3

Related Questions