2016-11-21 43 views
0

我必須編寫一個程序,使用while循環來詢問用戶看到了什麼鳥以及多少個這些問題,直到用戶輸入END並且循環停止允許它打印兩條消息,其中一條具有最常見的名字和數字。該程序可以工作,但打印出最後兩條消息時,不是打印該名稱,而是打印單詞END。我知道我需要一個變量來存儲常見的鳥,但我不知道該怎麼做。下面列出的是代碼。Java while循環,不能使用oop

{ 
    String BirdName; 
    String CommonBird=""; 
    int NumberOfTimes; 
    int mostNumberOfTimes = 0; 
    String quite = "END"; 

    Scanner Scanner = new Scanner(System.in); 

    while (true) 
    { 
     System.out.println("Which bird have you seen?"); 
     BirdName = Scanner.nextLine(); 

     if (BirdName.equals(quite)) 
     { 
      System.out.println("You saw "+ mostNumberOfTimes + " " + BirdName+ "."); 
      System.out.println("It was the most common bird seen at one time in your garden."); 
      break; 
     } 
     else 
     { 
      System.out.println("How many were in your garden at once?"); 
      NumberOfTimes = Integer.parseInt(Scanner.nextLine()); 

      if(mostNumberOfTimes < NumberOfTimes) 
      { 
       mostNumberOfTimes = NumberOfTimes; 
      } 
     } 
    } 
} 
+0

您需要添加另一個變量並將用戶看到的鳥存儲到該變量中。 – KPJAVA

回答

0

是的,你需要另一個變量來記錄最常見的鳥。您可以在更新mostNumberOfTimes的同時指定CommonBird,然後在輸出語句中使用它。

String birdName; 
String commonBird = ""; 
int numberOfTimes; 
int mostNumberOfTimes = 0; 
String quit = "END"; 

Scanner scanner = new Scanner(System.in); 

while (true) { 
    System.out.println("Which bird have you seen?"); 
    birdName = scanner.nextLine(); 

    if (birdName.equals(quit)) { 
     System.out.println("You saw " + mostNumberOfTimes + 
          " " + commonBird + "."); 
     System.out.println("It was the most common bird seen" + 
          " at one time in your garden."); 
     break; 
    } else { 
     System.out.println("How many were in your garden at once?"); 
     numberOfTimes = Integer.parseInt(scanner.nextLine()); 

     if (mostNumberOfTimes < numberOfTimes) { 
      mostNumberOfTimes = numberOfTimes; 
      commonBird = birdName; // added this 
     } 
    } 
} 

根據Java風格指南,變量名應始終以小寫字母開頭。只有類名應該有首字母大寫。

+0

謝謝,它工作 –