2012-11-22 33 views
0

我遇到了一個問題,它沒有打印出來,並且無法弄清楚它是什麼。沒有得到想要的結果,而且很卡住

現在我的代碼打印出這樣的:

***#

***##

***###

時,應打印出這樣的:

***#

**##

*###

這裏是我的代碼,目前的情況是:

import static java.lang.System.*; 

public class Box 
{ 
    private int size; 

public Box() 
{ 




} 

public Box(int count) 
{ 
    size = count; 
} 

public void setSize(int count) 
{ 
    size = count; 
} 

public int getSize() 
{ 
    return size; 
} 

public String toString() 
{ 
    String output=""; 
    for(int i = 1; i <= size; i++) 
    { 
     for(int k = size; k >0; k--) 
     { 
      output += "*"; 
     } 
     for(int j = size; j >size-i; j--) 
     { 
      output += "#"; 
     } 
     output += "\n"; 
    } 

    return output; 
} 
} 

和我的亞軍類交叉引用:

import static java.lang.System.*; 

import java.util.Scanner; 

public class Lab11e 
{ 
public static void main(String args[]) 
{ 
    Scanner keyboard = new Scanner(System.in); 
    String choice=""; 
     do{ 
      out.print("Enter the size of the box : "); 
      int big = keyboard.nextInt(); 
      //out.print("Enter a letter : "); 
      //String value = keyboard.next(); 

       //instantiate a TriangleFour object 
     Box box = new Box(big); 
      //call the toString method to print the triangle 
      System.out.println(box); 

      System.out.print("Do you want to enter more data? "); 
      choice=keyboard.next(); 
     }while(choice.equals("Y")||choice.equals("y")); 
} 
} 

我的想法是,我非常接近它,但只是無法弄清楚什麼。

+1

嘗試使用描述性的變量名。而不是我,j,k考慮行,列等。 – hoipolloi

+0

我正要離開與本實驗室相關的實驗室工作表,這就是原因。並且我不確定row,col等在這個實驗中是否適用 –

回答

1
for(int i = 1; i <= size; i++) 
    { 
     // Using a single for to make sure we don't create too many items. 
     // Also note the +1. It seems that when size = 3, you want 4 chars 
     // per line, so this take that extra char into account. 
     for(int k = 0; k < size + 1; k++) 
     { 
      // Use an if to decide if we print * or #. 
       // As 'i' gets bigger, we need to put less *, so 
       // we subtract 'i' from the total size. This tells 
       // when the midpoint has passed and we should start 
       // writing #s. 
      if (k <= size - i) 
       output += "*"; 
      else 
       output += "#"; 
     } 

     output += "\n"; 
    } 

解決方案有兩個內環:

for(int i = 1; i <= size; i++) 
    { 
     // Adds a number of * inversely proportional to the current 
     // value of 'i'. 
     for(int k = 0; k <= size - i; k++) 
     { 
      output += "*"; 
     } 

     // Start adding # where we stopped the *. 
     for(int j = size - i; j < size; j++) 
     { 
      output += "#"; 
     } 

     output += "\n"; 
    } 
+0

爲了以防萬一,有沒有辦法用2 for循環嵌套在主for循環中 –

+0

當然,只需將此版本添加到解。有點難以看出發生了什麼,但爲每個項目保存一個條件。 – BoppreH

+0

謝謝!這就是訣竅!感恩節快樂! –