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
  • 2

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
  • 11,326
  • 43
  • 62
  • 91
-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

Primata Lógico
  • 725
  • 4
  • 12