2014-09-29 60 views
1

我有一个基于用户输入的循环增量值任务。基于用户输入循环显示增量值

的任务是,下面的线在控制台

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

和线的量是由用户输入产生的决定。即如果用户在2它提供了以下的输出:

* 
** 

我当前的代码是:

import static javax.swing.JOptionPane.*; 
public class loop1 { 
    public static void main(String[] args){ 
     int current_line = 0; 
     String input_line = showInputDialog("type here "); 
     int target_line = Integer.parseInt(input_line); 
     while (current_line != target_line){ 
      String sign = "*"; 
      System.out.println(sign); 
      current_line ++; 
     } 
    } 
} 

但我似乎无法得到星号的数量(*),以增加每它运行的时间。我怎样才能做到这一点?

+1

(它会更容易下手为'(;;)'循环在这个问题)。 – user2864740 2014-09-29 18:29:31

+0

我真的建议在看这个http://mathbits.com/MathBits/Java/Looping/NestedFor .htm这是我会用的。 – StephenButtolph 2014-09-29 18:30:16

回答

3

你实际上在这里需要两个循环,但你只有一个。您有一个while循环可打印出星号,但您还需要一个循环来增加每次打印的星号数量。

一些伪代码可能看起来像:

For (int i = 1 to whatever value the user entered): 
    For (int j = 1 to i): 
     Print an asterisk 

实际的代码看起来像:

int numLines = Integer.parseInt(showInputDialog("type here ")); 
for(int numAsterisks = 0; numAsterisks < numLines; numAsterisks++) { 
    for(int i = 0; i < numAsterisks; i++) { 
     System.out.print("*"); 
    } 
    System.out.println(); // Start a new line 
} 
4

你需要一个嵌套循环。外循环的每次迭代(它是您已有的循环)将打印一行,并且内循环的每次迭代都会为当前行打印一个星号。

1

可以通过使用嵌套for循环使其更简单。修改您的循环为:

for (int i=0;i<target_line;i++) { 
    for (int j=0;j<=i;j++) { 
     System.out.print("*"); 
    } 
    System.out.println(); 
} 
0

您每次打印一个'*' - 符号。 你不一定需要两个循环。您可以将符号放置在循环外部,并且可以使用string.concat(“*”)在每次迭代中添加一个星号。连接实际上意味着将两个字符串合并为一个,所以实际上将来自上一次迭代的符号与新符号组合在一起。

int current_line = 0; 
String input_line = showInputDialog("type here "); 
int target_line = Integer.parseInt(input_line); 
String sign = "*"; 
while (current_line != target_line){ 
    sign.concat("*"); 
    System.out.println(sign); 
    current_line ++; 
}