0

I am trying to use try-catch statement in JAVA in a while loop, just to catch the exception when string input is given to nextInt, I don't know why it keeps on raising the exception after the first incorrect input.

Code

import java.util.Arrays;
import java.util.Scanner;
public class People{
        public static void main(String[] args){
                Scanner in=new Scanner(System.in);
                Scanner inS=new Scanner(System.in);
                int i=0;
                System.out.println("Enter number of people");
                int n=in.nextInt();
                int[] age=new int[n];
                String[] name=new String[n];
                double[] aIncome=new double[n];
                while (i<n){
                        try{

                                System.out.println(i+"Enter your last and first name (for e.g. if full name is \"Rahul Gupta\" then enter \"Gupta Rahul\") : ");
                                name[i]=inS.nextLine();
                                System.out.println("Now putting name");
                                System.out.println("Enter your age: ");
                                age[i]=in.nextInt();
                                System.out.println("Now putting age");
                                System.out.println("Enter your annual income: ");
                                aIncome[i]=in.nextDouble();
                                System.out.println("Now putting income");
                                i++;
                        }
                        catch(Exception InputMismatchException){
                                System.out.println("Error !! Wrong input, Please try again.");

                        }
                }
                System.out.println(Arrays.toString(age));
                System.out.println(Arrays.toString(name));
                System.out.println(Arrays.toString(aIncome));
        }
}

When correct input is given.

Script started on Sat 03 Feb 2018 07:55:42 PM NST
amehla@slbnen3000pc50:~/Desktop/test$ jva KKKava People.K
Enter number of people
3
0Enter your last and first name (for e.g. if full name is "Rahul Gupta" then enter "Gupta Rahul") : 
harit Gupta
Now putting name
Enter your age: 
26
Now putting age
Enter your annual income: 
59495
Now putting income
1Enter your last and first name (for e.g. if full name is "Rahul Gupta" then enter "Gupta Rahul") : 
Rahul Gupta
Now putting name
Enter your age: 
59
Now putting age
Enter your annual income: 
35695
Now putting income
2Enter your last and first name (for e.g. if full name is "Rahul Gupta" then enter "Gupta Rahul") : 
Shikha kom
Now putting name
Enter your age: 
56
Now putting age
Enter your annual income: 
59565
Now putting income
[26, 59, 56]
[harit Gupta, Rahul Gupta, Shikha kom]
[59495.0, 35695.0, 59565.0]

But when incorrect input is given, this goes on infinite times.

amehla@slbnen3000pc50:~/Desktop/test$ java People
Enter number of people
3
0Enter your last and first name (for e.g. if full name is "Rahul Gupta" then enter "Gupta Rahul") : 
Rahul Gupta
Now putting name
Enter your age: 
59
Now putting age
Enter your annual income: 
fasdf
Error !! Wrong input, Please try again.
0Enter your last and first name (for e.g. if full name is "Rahul Gupta" then enter "Gupta Rahul") : 
Rahul Gupta
Now putting name
Enter your age: 
Error !! Wrong input, Please try again.
0Enter your last and first name (for e.g. if full name is "Rahul Gupta" then enter "Gupta Rahul") : 
Rahu lasdf
Now putting name
Enter your age: 
Error !! Wrong input, Please try again.
0Enter your last and first name (for e.g. if full name is "Rahul Gupta" then enter "Gupta Rahul") : 
asdf adsf
Now putting name
Enter your age: 
Error !! Wrong input, Please try again.
0Enter your last and first name (for e.g. if full name is "Rahul Gupta" then enter "Gupta Rahul") : 
^Camehla@slbnen3000pc50:~/Desktop/test$ exit
exit

Script done on Sat 03 Feb 2018 07:57:22 PM NST

Would be a great help, Even if someone replies.

Thank You.

Atul Mehla
  • 11
  • 4
  • 3
    why on Earth are you calling a *variable* "InputMismatchException" (upper case)? – Andrey Tyukin Feb 03 '18 at 23:42
  • 1
    Possible duplicate of [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – Ivar Feb 03 '18 at 23:55
  • Adding a `in.nextLine();` in your catch might just fix it. – Ivar Feb 03 '18 at 23:56

4 Answers4

1

There's something weird going on with the newlines when you mix and match nextLine() and nextInt(), nextDouble() or any of those. If you replace the calls to nextInt() and nextDouble() in your code with Integer.valueOf(inS.nextLine()) and Double.valueOf(inS.nextLine()), that should fix your issue.

As a general rule, if you're reading any user input at the command line, you should read the entire line and parse the whole line. Don't try to grab individual tokens, it gets really messy.

Neatname
  • 94
  • 6
0

When you are typing your input value, you accept it by pressing Enter key. It generates new line character after the inputted value. When in some of next lines of codes you call nextLine() method, it reads the remaining new line character instead of input you type. To clear the new line character after calling nextInt() or nextDouble(), put nextLine() right after these methods.

Another possibility is to call methods like Integer.parseInt(in.nextLine()) or Double.parseDouble(in.nextLine()), as they automatically get rid of remaining new line character.

You should also think of putting in.nextLine() method in catch block to get rid of remaining new line character when input throwing an exception has been provided:

Another issue that is present in your code is this part:

catch(Exception InputMismatchException) {...}

With that code you catch ANY type of Exception - not only InputMismatchException but any other type inheriting from Exception class and Exception itself - first in the brackets goes class of Exception you want to catch and then the name you want to call it with within catch block - change it to:

catch(InputMismatchException ex ) {...}

That way you will catch only InputMismatchException.

Przemysław Moskal
  • 3,321
  • 2
  • 8
  • 20
0

I tried running your code, and I found three changes that will fix your problem.

First of all - you don't need two Scanners. Just use one. Get rid of in2 entirely.

Next - getting rid of in2 kind of messes up the line name[i]=inS.nextLine(); You can fix it by changing it to this: name[i]=in.next(); I'm not sure exactly why this fixes the problem, but here is my best guess (other users, please speak up if you know more about this!):

When you used nextLine(), the scanner was looking for everything before the next \n character. In the previous call to the scanner in the int n=in.nextInt(); line, the scanner only read in the number itself, and not the corresponding \n newline character which the user enters when they enter the number. Therefore, calling in.nextLine() will cause the Scanner to read in the same value that was meant to be the name again. We don't want that - we want to read in just the next token that the user enters, which next() does very nicely.

Lastly - I also changed the line catch(Exception InputMismatchException){... to the more conventional way of writing a catch statement: catch(InputMismatchException e){...

Keara
  • 549
  • 1
  • 8
  • 16
-1

I don't quite get the problem, but I guess what you want is to exit the loop after the first exception is thrown? Then instead of having

while (...) {
    try {
        ...
    } catch (...) {
        ...
    }
}

you can write

try {
    while (...) {
        ...
    }
} catch (...) {
    ...
}

or just add a break statement in your catch block to exit the surrounding while loop.

C. Miranda
  • 65
  • 1
  • 6