0

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?

bancqm
  • 71
  • 10
  • You might be looking for do-while, see [_The while and do-while Statements_ tutorial](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html); although that also has its problems with your specific use. – Mark Rotteveel Sep 05 '17 at 16:01
  • This code is flawed logically. – Aniket Inge Sep 05 '17 at 16:04
  • It's all about scanner [see here](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo?noredirect=1&lq=1) – Pmanglani Sep 05 '17 at 16:37

2 Answers2

0

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
    }
}
Nir Alfasi
  • 49,889
  • 11
  • 75
  • 119
0

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();
        }
    }
}
justMe
  • 1,622
  • 13
  • 20