2015-10-01 73 views
-2

說我想要做一些「塔」是這個樣子:乘法字符串

********* 
********* 
********* ******* 
********* ******* 
********* ******* *************** 
********* ******* *************** 
********* ******* *************** 
********* ******* *************** 
********* ******* *************** 
********* ******* *************** 
********* ******* *************** 

如果我要求用戶輸入三個不同的號碼爲塔的寬度和隨機整數將彌補長度,我怎麼能做一個循環,乘以「*」乘以用戶輸入的寬度數?這是我到目前爲止:

 for(int i = 0; i < randInt1; i++){ 

      // I would like to do something like 
      // System.out.print("*") * width1 
      // and do this for all three towers so that they 
      // print next to each other separated by a space 
     } 
+3

爲了讓回答者或其他有類似問題的人更容易,請編輯添加一個特定的問題陳述 - 「不起作用」可以假定,但* how *不起作用?什麼錯誤信息或不正確的行爲是特徵? –

+0

「長度」是什麼意思?它是每列的「高度」嗎? –

+0

@BingLu是這意味着高度。 – joanne72205

回答

1

用下面的代碼塊替換for循環應該可以工作。

int highest = Math.max(randInt1, Math.max(randInt2, randInt3)); 
for(int i = highest; i > 0; i--){ 
    printColumn(width1, randInt1, i); 
    System.out.print(" "); 

    printColumn(width2, randInt2, i); 
    System.out.print(" "); 

    printColumn(width3, randInt3, i); 
    System.out.println(); 
} 

並增加一個輔助方法

private static void printColumn(int columnWidth, int columnHeight, int currentHeight) { 
    for(int j = columnWidth;j > 0;j--) { 
     if(columnHeight - currentHeight >= 0) { 
      System.out.print("*"); 
     } else { 
      System.out.print(" "); 
     } 
    } 
} 

你不能夠 「乘」, 「*」 S。您可能需要逐行打印您的塔,並使用空間來對齊每一列。

+0

如果您將重構內部for-loop以避免代碼重複 - 您將獲得我的投票;) – alfasin

+0

更好 - 這是要走的路! :) – alfasin

+0

@alfasin謝謝! –

0

另一種解決方案將連接每個星的每個星或每個塔的空白。請注意0​​,它會在相關塔的寬度處返回一個字符串!

public static void main(String[] args) { 

    // hardcoded settings (example) 
    // in your case you'll read it from the user 
    Integer[] widths = {5, 4, 6}; 
    Integer[] heights = {5, 4, 6}; 

    // subtract max-1 from the heights 
    int max = Collections.max(Arrays.asList(heights)) - 1; 
    for (int i=0; i<heights.length; i++) 
     heights[i] -= max; 


    // print the towers 
    for (int i=0; i<max; i++){ 
     String line = ""; 
     for (int j=0; j<widths.length; j++) { 
      if (heights[j] > 0) 
       line += generateString("*", widths[j]) + " "; 
      else 
       line += generateString(" ", widths[j]) + " "; 
      heights[j] += 1; 
     } 
     System.out.println(line); 
    } 
} 

private static String generateString(String str, int times) { 
    return String.format("%1$" + times + "s", str).replace(" ", str); 
}