2011-12-09 127 views
0

我正在学习java,使用本书“Java如何编程”。我正在解决练习。在这个实际的练习中,我应该创建一个从用户读取一个整数的程序。程序应该显示与用户读取的整数相对应的星号(*)。 F.eks用户输入的整数3,程序应该再显示:“While循环”不能正常工作

*** 
*** 
*** 

我尝试窝内另一个while语句,重复在一行中的星号的第一个,另外一个重复这个适量的时间。不幸的是,我只能让程序显示一行。有谁能告诉我我做错了吗? 的代码如下:

import java.util.Scanner; 
public class Oppgave618 
{ 

    public static void main(String[] args) 
    { 
    int numberOfSquares; 
    Scanner input = new Scanner(System.in); 
    System.out.print("Type number of asterixes to make the square: "); 
    numberOfSquares = input.nextInt(); 

     int count1 = 1; 
    int count2 = 1; 

    while (count2 <= numberOfSquares) 

     { 
     while (count1 <= numberOfSquares) 
      { 
      System.out.print("*"); 
      count1++; 
      } 
     System.out.println(); 
     count2++; 
     } 

    } 

} 

回答

5

你应该在外部循环的每次迭代

public static void main(String[] args) { 
    int numberOfSquares; 
    Scanner input = new Scanner(System.in); 
    System.out.print("Type number of asterixes to make the square: "); 
    numberOfSquares = input.nextInt(); 
      //omitted declaration of count1 here 
    int count2 = 1; 
    while (count2 <= numberOfSquares) { 
     int count1 = 1; //declaring and resetting count1 here 
     while (count1 <= numberOfSquares) { 
      System.out.print("*"); 
      count1++; 
     } 
     System.out.println(); 
     count2++; 
    } 
} 
+0

谢谢!这解决了它:-) – user820913

+0

不客气。祝你好运Java! – amit

1

count1需要重置每次移动到下一行的时间,例如复位count1

while (count2 <= numberOfSquares) 
{ 
    while (count1 <= numberOfSquares) 
    { 
     System.out.print("*"); 
     count1++; 
    } 
    System.out.println(); 
    count1 = 1; //set count1 back to 1 
    count2++; 
} 
1

除非练习需要while循环,否则实际上应该使用for循环。他们实际上会防止这些错误的发生,并且需要更少的代码。而且,在大多数编程语言习惯从零开始计数和使用<而不是<=终止循环:

for (int count2 = 0; count2 < numberOfSquares; ++count2) 
{ 
    for (int count1 = 0; count1 < numberOfSquares; ++count1) 
     System.out.print("*"); 
    System.out.println(); 
} 
+0

谢谢,这是一个好点! – user820913