0

So I started learning java yesterday and I was trying to get the user to enter "5" and keep repeating until he/she got it. To prevent the program from crashing when you input a string I made the if/else statement. Everything works fine but when a person enters a int first then a string after it repeats the prompt "Enter the number 5 : " twice ! What am I doing wrong??

import java.util.Scanner;

public class chakad {
    public static void main(String[] args) {
        int number = 1;
        Scanner input = new Scanner(System.in);

        while (number != 5) {
            System.out.println("Enter the number 5: ");
            if (input.hasNextInt()) {
                number = input.nextInt();
            } else {
                System.out.println("woops");
                input.nextLine();
            }
        }

        System.out.println("YOU DID IT!");

        input.delimiter();

    }
}
ChaKaD
  • 9
  • 1

2 Answers2

0

It seems to work correctly modifying your code like this :

        if (input.hasNextInt()) {
            number = input.nextInt();
        } else if (input.hasNext()) {
            System.out.println("woops");
            input.next();
        }

Best Regards,

Michel.

mpromonet
  • 10,379
  • 42
  • 54
  • 85
-1

You can use this code to read a line instead:

 InputStreamReader fr = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(fr);
    try {
           choice = br.readLine();
        } catch (Exception e) {
        e.printStackTrace();
        }

Of course you have to import the libraries:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

The try-catch statement is just to make sure no problems occur. Hope that helped

gNazi
  • 653
  • 4
  • 12
  • There is no problem with the scanner ... – Maciej Cygan Jan 03 '14 at 23:03
  • I don't see any issue with the scanner... – Adarsh Shah Jan 03 '14 at 23:20
  • Your absolutely right, im sorry , I used to think there was a problem with it, but after reading the following post: http://stackoverflow.com/questions/7056749/scanner-issue-when-using-nextline-after-nextxxx turns out it only does as instructed – gNazi Jan 03 '14 at 23:37