0

I'm new to java and am trying to validate numbers being entered into the console. I want an integer, but I know if a letter is entered for example an error would occur, so I thought I'd use try & catch. This works if try and do it first time round, but I want to loop through until the user inputs a valid integer. Got this working, but when I get a valid number and print out the number I get a list of all attempts.... Hope this makes sense

import java.util.Scanner;
public class ConvertStringInt {

    public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int i = 0;
    System.out.print("Enter a whole number: ");
    try {
      i = sc.nextInt();
    } catch (Exception e){
      System.out.println("Error");
      main(args);
    }
    
    System.out.println(i);
    
  }
}

Here is the output from the console....

Enter a whole number: a

Error

Enter a whole number: d

Error

Enter a whole number: 2.0

Error Enter a whole number: 1

1

0

0

0

Could somebody please explain this?

Thanks in advance

Neil

Community
  • 1
  • 1
Neil White
  • 89
  • 2
  • 15

2 Answers2

2

You are seeing outputs for each input because you call main recursively. If you immediately type a correct int, the flow is this:

main
  ask for input -> int
  print i (1)

But in your case the input is not an int. This is what happens: you type the first input, it fails. You do not print yet because you first call main again, asking for the next input. Only when you get a correct int you print, and then finish and allow the previous main-execution to finish by printing, which then allows the previous... and so on:

main(args)
    ask for input -> a !int
    main(args)
        ask for input -> d !int
        main(args)
            ask for input -> 2.0 !int
            main(args)
                ask for input -> 1 int
                print 1 (1)
            print 0 (2.0)
        print 0 (d)
    print 0 (a)

Look at Ravi's answer for a proper way to repeatedly ask for input without using try/catch (which is discouraged).

Malte Hartwig
  • 4,206
  • 2
  • 11
  • 30
1

You could check for integer token in loop

while (!sc.hasNextInt()) // loop until next token is integer
{
    // do something or print error
     System.out.println(sc.next() +"is not number");
}

i = sc.nextInt();
Ravi
  • 28,657
  • 41
  • 110
  • 158