2017-05-11 88 views
1

所以我想用netbeans 8.1在Java中用行和列創建一個基本的2d數組。我的簡單2D數組問題

這是我的代碼:

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

有人能幫助我瞭解什麼是錯的?

+6

你知道println和print之間的區別嗎? –

+0

哦!非常感謝!我沒有注意到這一點。一定是完成了習慣哈哈。 – badweight

+0

如果您的問題是旋轉的,請將答案標記爲已解決。 –

回答

3

看來你應該使用print結合println,見下圖:

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