简体   繁体   中英

While Loop in Java with ending condition

I am trying to complete a assignment from a online Java Tutorial and I am currently on a question regarding While Loops. This is my code:

import java.util.Scanner;

public class bird {
    public static void main(String[] args){
        Scanner bucky = new Scanner(System.in);
        final String end = "END";
        String bird;
        int amount;

        System.out.println("What bird did you see in your garden? ");
        bird = bucky.nextLine();

        while(!(bird.equals(end))){
            System.out.println("How many were in your garden? ");
            amount = bucky.nextInt();

        }
    }
}

My problem is the code is meant to terminate if END is inputted by the user so it needs to be outside the While Loop. But without it being inside the loop, it doesn't repeat the question for more types of birds. Is there a way to have the first "What bird did you see? " inside the loop whilst also having a condition that exits the loop if the Ending condition is met?

One way to do it (see code comments):

public static void main(String[] args){
    Scanner bucky = new Scanner(System.in);
    final String end = "END";
    String bird;
    int amount;

    while(true){ // loop "forever"
        System.out.println("What bird did you see in your garden? ");
        bird = bucky.nextLine();
        if (end.equals(bird)) { // break out if END is entered
            break;
        }

        System.out.println("How many were in your garden? ");
        amount = bucky.nextInt();
        bucky.nextLine(); // consume the newline character after the number

        System.out.println("we saw " + amount + " of " + bird); // for debugging
    }
}

Try this quick solution:

import java.util.Scanner;

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

        Scanner bucky = new Scanner(System.in);
        System.out.println("What bird did you see in your garden? ");

        while(!(bucky.nextLine().equalsIgnoreCase("END"))){
            System.out.println("How many were in your garden? ");
            bucky.nextInt();
            System.out.println("What bird did you see in your garden? ");
            bucky.nextLine();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM