2016-11-21 138 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

谢谢,它工作 –