Java – unlimited when trying catch

I encountered a problem when I tried to execute a try catch statement in a loop I ask the user to input letters first and then a number. If he inputs the number correctly, the program ends If he enters letters instead of numbers, the program should say "please enter numbers if there is an error" and ask the user to enter numbers again, but each time he enters letters instead of numbers, the program enters an infinite loop and does not allow me to enter new values

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);

    }

}

Solution

This is your problem If the user enters a non number where you want to enter a number, your nextint() will throw an exception, but will not delete the letter from the input stream!

This means that when you loop back to get the number again, the letter will still exist and your nextint () will throw an exception again Wait, indefinitely (or at least until the heat of the universe dies, or the machine finally crashes, whichever comes first)

One way to solve this problem is to actually read / skip the next character when nextint() fails in order to delete it from the input stream You can basically use scanner findInLine(“.”) Do this until scanner Hasnextint() returns true

The following code shows a method:

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);
     }
}

The following transcripts show its practical effect:

Enter letter,number: Abcde42
Ignoring 'b'
Ignoring 'c'
Ignoring 'd'
Ignoring 'e'
Got 'A' and 42
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>