billies weasley billies weasley - 7 days ago 7
Java Question

very basic programme using while loop and if statement compiles but does not work-i think its all correct?

The programme should repeatedly ask the user which and how many of a bird he/she has seen until they say end, it should store the most numerous bird seen then output which bird was seen the most.

When run, the program asks the questions, then when end is typed the output is always "You saw 'x' ; It was the most common bird seen at one time in your garden." The output does not display which bird was most popular-why?

import java.util.Scanner;

class birds {
public static void main(String[] args) {

questions();

}// end main method

public static void questions() {
int largest = 0;
String popularBird = "";
while (true) {
Scanner scanner = new Scanner(System.in);
System.out.println("Which bird have you seen?");
String answerBird = scanner.nextLine();

if (answerBird.equalsIgnoreCase("end")) {
System.out.println("You saw " + largest + " " + popularBird);
System.out.println("It was the most common bird seen at one time in your garden.");
break;
}//end if statement

System.out.println("How many were in your graden at once?");
int answerNumber = scanner.nextInt();

if(largest < answerNumber) {
largest = answerNumber;
answerBird = popularBird;
}



}//end while loop

return;
}// end method questions

}// end class bird

Answer

You should declare the scanner, largest and popularBird variables outside the while loop as in your current code, they are getting overwritten/replaced in each iteration.

You can refer the below code with inline comments:

//declare the variables outside the loop
int largest = 0;
String popularBird = "";
Scanner scanner = new Scanner(System.in);//use the same scanner

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

     if (answerBird.equalsIgnoreCase("end")) {
                  System.out.println("You saw " + largest + " " + popularBird);
                   System.out.println("It was the most 
                         common bird seen at one time in your garden.");
                       break;
      }//end if statement

     System.out.println("How many were in your graden at once?");            
     int answerNumber = Integer.parseInt(scanner.nextLine());

     if(largest < answerNumber) {
                        largest = answerNumber;
                        popularBird  = answerBird;
              }
            }
     } finally {
            if(scanner != null)
               scanner.close();//close the scanner
         }
     }
Comments