2014-02-28 162 views
0

這是此作業中的主要步驟。如果輸入有效,則創建嵌套循環以便以表格格式輸出 數字。第一個輸入i定義了行數
,第二個輸入j定義了列數。在循環內, 編寫代碼以列出從1到i * j的正數。整數和字符串使用 System.out.printf()函數,其中「%4d」和「%4s」格式用於 整數和字符串。使用Java格式化表格

我需要打印出

設置表和數據類型的大小(鍵入 'Q' 或 'Q' 退出): 3 4 「數字」

  • | 1 2 3 4

------------- ------

1 | 1 2 3 4

2 | 5 6 7 8

3 | 9 10 11 12

我設置了列數和行數後,我只能得到內部表格,而不是外部數字表格或星星。 爲了得到它,以顯示正確,我不得不改變它,但它應該列隊整齊

Scanner scan = new Scanner(System.in); 
    String stringIn; 

    do 
    { 
     System.out.print("Set the size of table and data-type(Type Q or q to quit)"); 
     stringIn = scan.nextLine(); 
     int space = stringIn.indexOf(" "); 
     int spaceTwo = stringIn.indexOf(" ", space+1); 

     if(stringIn.length()>4) 
     { 

      String firstNum = stringIn.substring(0,space); 
      String secondNum = stringIn.substring(space+1,spaceTwo); 
      String dataType = stringIn.substring(spaceTwo+1); 
      int firstInt = Integer.parseInt(firstNum); 
      int secondInt = Integer.parseInt(secondNum); 

      if (!stringIn.equals("Q")&&!stringIn.equals("q")&&firstInt>=0&&secondInt>=0) 
      { 
       System.out.println(stringIn.substring(0,space) + " " + stringIn.substring(space+1,spaceTwo) + " " + stringIn.substring(spaceTwo+1)); 
      } 
      else if(firstInt<0||secondInt<0) 
      { 
       System.out.println("Try again. The input was invalid"); 
      } 
      for(int i = 1; i <firstInt+1; i++) 
      { 
       for (int j = 1; j < secondInt+1; j++) 
       { 
        System.out.printf("%4d", i*j); 
        System.out.printf("%4s", i*j); 
       } 
       System.out.println(); 
      } 
     } 

    } 
    while(!stringIn.equals("Q")&&!stringIn.equals("q")); 

這是我的第一個Java類,所以我的代碼很凌亂。

回答

1

你非常接近,只是一點關閉你的嵌套循環中的邏輯。這就是我改性:

1)移到創建一個計數器以用於細胞內循環

2)以外的列標籤值

3)使用計數器來打印單元格的值&然後遞增它

代碼:

String headerRow= " * |"; 
String spacer = "-----"; 
for(int i=1; i<secondInt + 1; i++){headerRow+=" "+i; spacer+="----";} 
System.out.println(headerRow); 
System.out.println(spacer); 
int counter = 1; 
for (int i = 1; i < firstInt + 1; i++) { 
    System.out.printf("%4s", i + " |"); 
    for (int j = 1; j < secondInt + 1; j++) { 
     System.out.printf("%4d", counter); 
     counter++; 
    } 
    System.out.println(); 
} 

該代碼輸出該:

> 4 5 numbers 
* | 1 2 3 4 5 
> ------------------------- 
1 | 1 2 3 4 5 
2 | 6 7 8 9 10 
3 | 11 12 13 14 15 
4 | 16 17 18 19 20 
+0

謝謝,這是一個很大的幫助,但我怎麼會得到頂行顯示「* | 1 2 3 4「(行號)」--------------「,在 – user3363245

+0

下面有一個分隔符我用循環上面的幾條'System.out.println'語句更新了答案,應該得到你後面的東西! – Durandal

+0

謝謝,但我想要得到的是與表增長的東西,如果我選擇使它超過4列,我不知道如何得到該輸出,頂行需要成爲一個列計數器,所以如果有3個,它會上升到4,5個等。 – user3363245