Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Scanner gets integer input second time

I should check if the input value equals ‘end’ or a number..

I tried this but it reads integer value only second time I enter.

Scanner scan = new Scanner(System.in);

    while (play){
       int answer = ask();

        if (scan.next().equals("end")){
            System.out.println("ended");
            play = false;
        } else if (scan.hasNextInt())
        {
            int number = scan.nextInt();
            if (number == answer){...

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This happens because scan.next() is taking the value to check if it’s equals to "end", so the second condition fails because there’s no next value (until there is).
You can fix the problem by swapping the conditions:

Scanner scan = new Scanner(System.in);

    while (play){
       int answer = ask();

        if (scan.hasNextInt()) {
            int number = scan.nextInt();
            if (number == answer) System.out.println("correct");
        } else if (scan.next().equals("end")){
            System.out.println("ended");
            play = false;
        } 
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading