dimanche 27 novembre 2016

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 0 ; It was the most common bird seen at one time in your garden." even when the while loop has run several times which means the second if statment is not being executed-but why?

import java.util.Scanner;

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

        questions();

    }// end main method

    public static void questions() {

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

            int largest = 0;
            String popularBird = "";

            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

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

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



        }//end while loop

    return;
    }// end method questions

}// end class bird

Aucun commentaire:

Enregistrer un commentaire