2014-09-18 65 views
0

我想將此循環打印到N 10 * N 100 * N等下的一個表格中。我可以使循環工作,但我無法弄清間距以將我的值移動到正確的。我更新,所以任何幫助,將不勝感激。將一個循環打印到表格

package Exercises; 

public class TabularOutput { 

    public static void main(String[] args) 
    { 
     //initialize variables 
     int w = 0; 
     int x = 0; 
     int y = 0; 
     int z = 0; 

     System.out.println("N  10*N  100*N  1000*N\n"); 

     while(w<=4) 
     { 
      int a = w + 1; 
      System.out.println(a); 
      ++w; 
     } 
     while(x<=4) 
     { 
      int b = (x + 1) * 10; 
      System.out.println(b); 
      ++x; 
     } 
     while(y<=4) 
     { 
      int c = (y + 1) * 100; 
      System.out.println(c); 
      ++y; 
     } 
     while(z<=4) 
     { 
      int d = (z + 1) * 1000; 
      System.out.println(d); 
      ++z; 
     } 


    }//end method main 

}//end class TabularOutput 
+0

你所要求的被稱爲字符串填充。 [這](http://stackoverflow.com/questions/388461/how-can-i-pad-a-string-in-java)是一個先前的問題,你可以通讀。 – Compass 2014-09-18 18:26:40

+0

問題是,您打印的東西順序錯誤。您需要在同一行上打印N,10 * N,100 * N和1000 * N,而不是在每個單獨的循環中打印。 – Barmar 2014-09-18 18:28:15

回答

2

試試這個:

int a=0, b=0, c=0, d=0; 

while(w<=4) 
    { 
     a = w + 1; 
     System.out.print(a); 
     ++w; 

     b = (x + 1) * 10; 
     System.out.print("\t"+b); 
     ++x; 

     c = (y + 1) * 100; 
     System.out.print("\t"+c); 
     ++y; 

     d = (z + 1) * 1000; 
     System.out.println("\t"+d); 
     ++z; 

    }