3

I have a problem when trying to execute try-catch statement inside do while loop.I ask user to first enter letter and then a number and if he enters number correctly the program ends.If he enters letter instead of number the program should say "An error occurred please enter number " and ask user to enter number again but every time i type letter instead of number the program goes into an infinite loop and won't allow me to enter new value. And just goes "An error occurred you must enter number" "Please enter number".

public class OmaBrisem {

    public static void main(String[] args) {
        Scanner tastatura = new Scanner(System.in);
        boolean b = true;
        int a = 0;
        String r = "";
        System.out.println("Please enter a letter");
        r = tastatura.next();
        do {
            try {
                System.out.println("Please enter numerical value");
                a = tastatura.nextInt();
                b = true;
            } catch (Exception e) {
                System.out.println("An error occured you must enter number");
                b = false;
            }
        } while (!b);

    }

}
piyushj
  • 1,546
  • 5
  • 21
  • 29
Stanimir
  • 51
  • 6

4 Answers4

6

Here's your problem. If the user enters a non-number where you expect a number, your nextInt() will raise an exception but it will not remove the letter from the input stream!

That means when you loop back to get the number again, the letter will still be there and your nextInt() will once again raise an exception. And so on, ad infinitum (or at least until the heat death of the universe, or the machine finally breaks down, whichever comes first).

One way to fix this would be to actually read/skip the next character when nextInt() fails so that it's removed from the input stream. You could basically do this with Scanner.findInLine(".") until Scanner.hasNextInt() returns true.

The following code shows one way to do this:

import java.util.Scanner;
public class MyTestProg {
     public static void main(String [] args) {
         Scanner inputScanner = new Scanner(System.in);
         System.out.print("Enter letter, number: ");

         // Get character, handling newlines as needed

         String str = inputScanner.findInLine(".");
         while (str == null) {
             str = inputScanner.nextLine();
             str = inputScanner.findInLine(".");
         }

         // Skip characters (incl. newline) until int available.

         while (! inputScanner.hasNextInt()) {
             String junk = inputScanner.findInLine(".");
             if (junk == null) {
                 junk = inputScanner.nextLine();
             }
             System.out.println("Ignoring '" + junk + "'");
         }

         // Get integer and print both.

         int num = inputScanner.nextInt();
         System.out.println("Got '" + str + "' and " + num);
     }
}

And the following transcript shows it in action:

Enter letter, number: Abcde42
Ignoring 'b'
Ignoring 'c'
Ignoring 'd'
Ignoring 'e'
Got 'A' and 42
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • I do like the *until the heat death of the universe, or the machine finally breaks down, whichever comes first* – Serge Ballesta May 20 '16 at 07:41
  • When you enter two letters at the same time your code also runs into an infinite while loop – HasS May 20 '16 at 08:50
  • 1
    @HasS, yes, when there's an intervening newline which makes `findInLine` fail. - I only tested with a single line. Though the code was only meant as a sample to illustrate the concept, I've fixed with an update. If there's *still* an issue, please let me know the exact test data you're using. – paxdiablo May 20 '16 at 11:40
  • That solution you gave is perfectly ok but what you are doing is taking only single Character at first line and single character at second line .. i hope that helps the dude who asked @paxdiablo – HasS May 20 '16 at 13:01
1

I realized that my program ignores the Scanner object tastatura in try block whenever i insert wrong value and do while loop starts again so i created new object of Scanner class and called it tastatura2 and my program works fine.

Scanner tastatura = new Scanner(System.in);
        boolean b = true;
        int a = 0;
        String r = "";
        System.out.println("Please enter a letter");
        r = tastatura.next();
        do {
            try {
                Scanner tastatura2 = new Scanner(System.in);
                System.out.println("Please enter numerical value");
                a = tastatura2.nextInt();
                b = true;
            } catch (Exception e) {
                System.out.println("An error occured you must enter number");
                b = false;
            }
        } while (!b);
Stanimir
  • 51
  • 6
  • Sometimes using only a Scanner for input leads to errors , that happened to me many times – HasS May 20 '16 at 10:39
0

Just add tastatura.nextLine() in the catch block to discard the last input.

Logos
  • 334
  • 1
  • 7
  • 17
  • That's not bad, assuming you're happy to discard the entire rest of the line. I prefer a more localised approach but, assuming you make it clear on the possible effect, this will work as well. – paxdiablo May 20 '16 at 07:52
0

You can get out of the loop by break; when the Exception is caught ... So just add :

            break;

on your catch Block :)

The catch clause would look like this :

catch (Exception e) {
            System.out.println("An error occured you must enter number");
            b = false;
            break;
        }
HasS
  • 201
  • 1
  • 17