Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, try-catch with Scanner

I am creating a small algorithm and this is a part of it.

If the user enters non integer values, I want to output a message and let the user enter a number again:

boolean wenttocatch;

do 
{
    try 
    {
        wenttocatch = false;
        number_of_rigons = sc.nextInt(); // sc is an object of scanner class 
    } 
    catch (Exception e) 
    {
        wenttocatch=true;
        System.out.println("xx");
    }
} while (wenttocatch==true);

I am getting a never ending loop and I can't figure out why.

How can I identify if the user enters some non integer number?
If the user enters a non integer number, how can I ask the user to enter again?

Update
When I am printing the exception I get 'InputMismatchException', what should I do?

like image 411
pavithra Avatar asked Sep 15 '15 18:09

pavithra


People also ask

Can you use a Scanner in a method Java?

The Scanner class is mainly used to get the user input, and it belongs to the java. util package. In order to use the Scanner class, you can create an object of the class and use any of the Scanner class methods. In the below example, I am using the nextLine() method, which is used to read Strings.

What can I use instead of try catch in Java?

But anyhow, even without them, Vavr Try is a real alternative for Java try-catch blocks if you want to write more functional-style code.

What is try catch in Java with example?

Java try and catchThe try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.


2 Answers

You dont have to do a try catch. This code will do the trick for you :

public static void main(String[] args) {
    boolean wenttocatch = false;
    Scanner scan = new Scanner(System.in);
    int number_of_rigons = 0;
    do{
        System.out.print("Enter a number : ");
        if(scan.hasNextInt()){
            number_of_rigons = scan.nextInt();
            wenttocatch = true;
        }else{
            scan.nextLine();
            System.out.println("Enter a valid Integer value");
        }
    }while(!wenttocatch);
}
like image 66
Yassine.b Avatar answered Nov 09 '22 09:11

Yassine.b


The Scanner does not advance until the item is being read. This is mentioned in Scanner JavaDoc. Hence, you may just read the value off using .next() method or check if hasInt() before reading int value.

boolean wenttocatch;
int number_of_rigons = 0;
Scanner sc = new Scanner(System.in);

do {
    try {
        wenttocatch = false;
        number_of_rigons = sc.nextInt(); // sc is an object of scanner class
    } catch (InputMismatchException e) {
        sc.next();
        wenttocatch = true;
        System.out.println("xx");
    }
} while (wenttocatch == true);
like image 32
James Jithin Avatar answered Nov 09 '22 11:11

James Jithin