2013-09-29 52 views
1

我打印0-99的值和食物數組中的一個隨機字符串。我似乎無法正確輸出它們到表格。初學java - 打印表格

String foods[] = {"Bread", "Pizza", "Cheese"}; 
for (int x = 0; x<=99; x++) { 
     for (int i = 0; i<4; i++) { 
      int random = (int) (Math.random() * 3); 
      System.out.print(x + " - " + foods[random] + "\t\t"); 
     } 
    System.out.println(); 
} 

實際輸出:

0 - Pizza  0 - Bread  0 - Cheese 0 - Bread 
1 - Bread  1 - Pizza  1 - Bread  1 - Pizza 
.... until 99 

預期輸出:

0 - Pizza  1 - Bread  2 - Cheese 3 - Bread 
4 - Bread  5 - Pizza  6 - Bread  7 - Pizza 
.... until 99 
+2

是什麼你要找的則輸出? – Rogue

+0

在另一個註釋中:嘗試在所有代碼中保持一致。在這種情況下,在for語句中,始終使用'<'或'<='但不要混淆,這會在將來幫助您,在執行更復雜的代碼時提高可讀性。 –

回答

1

的問題是你只有在遞增x內部用於運行並打印整行。

String foods[] = {"Bread", "Pizza", "Cheese"}; 
    for (int x = 0; x <= 99;) { 
     for (int i = 0; i < 4; i++) { 
      int random = (int) (Math.random() * 3); 
      System.out.print(x + " - " + foods[random] + "\t\t"); 
      x++; 
     } 
     System.out.println(); 
    } 

您必須在內部增加x。

1

這將做的工作:

String foods[] = {"Bread", "Pizza", "Cheese"}; 
    for (int x = 1; x<=100; x++) { 

       int random = (int) (Math.random() * 3); 
       System.out.print((x-1) + " - " + foods[random] + "\t\t"); 
       if(x%4==0) 
        System.out.println(); 


    } 
0

試試這個代碼

import java.io.*; 
class dev 
{ 
public static void main (String[] args) 
{ 
    String foods[] = {"Bread", "Pizza", "Cheese"}; 
     for (int x = 0; x<=99; x++) 
      { 
      System.out.print(x + " -" + foods[ (int) (Math.random() * 3)] + " \t\t"); 
       if(x%4==0) System.out.println(); 
      } 
}} 
+1

-1只是別人的便宜副本答案。 –