Data Validation and Scanners in Java

I have a question regarding data validation and scanners. The following code snippet checks for userinput. Everything except the whole is not allowed, and the user is prompted to re-enter the value. My question is that the code only works if the scanner is declared inside the while loop. The program runs endlessly if the scanner is declared outside. Why is this? Thank.

int UserInp;
    boolean dataType=false;
    while(dataType==false)
    {
        Scanner sc=new Scanner(System.in);
        try
        {

    System.out.print("\nEnter a number: ");
    UserInp=sc.nextInt();

    dataType=true;
        }
        catch(Exception JavaInputMismatch)
        {

            System.out.println("Option not available.Try again.");

        }

    }
+4
source share
3 answers

An interesting problem!

What happens is that the scanner tries to translate a non-integer into an integer and realizes that it cannot, so it throws an InputMismatchException. However, he moves past the marker if the transfer was successful.

, , , , nextInt(). dataType true, .

, catch :

catch(Exception JavaInputMismatch){
    System.out.println( sc.next() );
    System.out.println("Option not available.Try again.");
}

, :

Enter a number: hello
hello
Option not available.Try again.

Enter a number:

. , next() , . nextInt() .

, , , , , ; , "", , - .

, , , , .

+5

Purag , nextLine() .

, catch :

catch(Exception JavaInputMismatch)
    {
        System.out.println("Option not available.Try again.");
        sc.nextLine();
    }
+1

.

!

. Scanner object , while loop. .

Scanner , ( String) Scanner , . , .

. next() Scanner , , nextInt(), nextFloat() ..,

0

All Articles