2011-12-09 130 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