我的简单2D数组的问题

时间:2017-05-11 01:23:42

标签: java arrays

所以我尝试使用netbeans 8.1在Java中创建一个带行和列的基本二维数组。

这是我的代码:

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

但由于某种原因,输出看起来像这样:

output

有人可以帮我理解错误吗?

2 个答案:

答案 0 :(得分:3)

您似乎应该将printprintln结合使用,请参阅以下内容:

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.
    }
}

答案 1 :(得分:0)

我发现dat3450's answer已足以解决您的问题,但System.out.println("");让我感到有点恼火。 所以,我就是这样做的:

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