2012-12-06 182 views
3

我有一個任務來創建一個程序,提示用戶輸入一個整數,然後根據用戶輸入使用while循環創建一個乘法表。Java - 在一行中輸出用戶輸入整數的整數

輸出乘法表必須包含標題行和列。我堅持的是如何創建標題行,因爲標題必須計算的數字取決於用戶輸入。

我在while循環中創建了標題列,該循環對行進行格式化,因爲每次循環逐步完成時都會創建一個新行。但標題行只打印一次,因此我不能使用格式化列創建它的while循環。

如何創建標題行,以便將用戶輸入遞減爲1,並輸出來自1,2,3,...用戶輸入的所有整數值?

這是我有:

import java.util.Scanner; 
public class Multiplication 
{ 
    public static void main(String[] args) 
    { 
    int number; 
    String yesno = "Y"; 
    Scanner keyboard = new Scanner(System.in); 
    System.out.print ("This program generates a multiplication table "); 
    System.out.println("based on a number you enter."); 


    while(yesno.equalsIgnoreCase("Y")) 
    { 
     System.out.println("Please enter a number."); 
     number = keyboard.nextInt(); 

     int row = 1; 
     int column = 1; 

     System.out.println(" |" + MAKETHISWORK + "\t"); //THIS IS WHERE I'M STUCK. 
     System.out.println("--------------------");   

     while(number>0) 
     {  
      row = 1; 
      while(row <= number) 
      { 
       System.out.print(row + "|"); 

       column = 1; 
       while(column <= number) 
       { 

        System.out.print(row*column + "\t"); 
        column ++; 

       } //END WHILE COLUMN <= NUMBER 
       System.out.println(); 
       row ++; 

      } //END WHILE ROW <=NUMBER 
      System.out.println(); 

      while(number>0) 
      { 
       number--; 
      } 

     } //END WHILE NUMBER >0 

     System.out.println("Would you like to enter another number? (Y/N) "); 
     yesno = keyboard.nextLine(); 
     yesno = keyboard.nextLine(); 
    } //END WHILE YESNO IS Y 

    while(yesno.equalsIgnoreCase("N")) 
    { 
     System.out.println("Thanks for participating!"); 
     break; 
    } 
} 
} 

回答

2

爲什麼不直接使用另一個循環建立一個字符串,該值?

StringBuilder builder = new StringBuilder(); 
for (int i = 1; i <= number; i++) { 
    builder.append(i).append(" "); 
} 
System.out.println(" |" + builder.toString() + "\t"); 

注意這將創造數以空格分隔字符串,最多輸入一個。如果你想要一個不同的分隔符,只需附加一個不同的值。

+0

感謝您的反饋! – ajanic0le