Looping do ... so far the uncertainty

In the catch block, I'm trying to fix user errors. When testing, if I use the keyword "break", it does not go to the original question. If I use "continue", it loops endlessly. "Sc.next ();" doesn't seem to allow this.

Here is the relevant piece of code.

public class ComputerAge {
    private static int age;
    private static int year;
    private static int month;
    private static int date;
    private static Calendar birthdate;

    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.print("Enter the numeral representing your birth month: ");
        do {
            try {
                month = sc.nextInt();
            } catch (InputMismatchException ime){
                System.out.println("Your respone must be a whole number");
                break;
            }
        } while (!sc.hasNextInt());
+4
source share
5 answers

To solve the problem, we must determine what we want to achieve in the end.
We want the month to be a numeric month, i.e. a number> 0.

In this way:

  • If the user fills in the correct number month, it will be filled.
  • Exception month "0".

: , , 0.

:

:

while (month == 0);

break sc.next().

+3

, sc.nextInt() , Scanner . , sc.next() catch break:

do {
    try {
        month = sc.nextInt();
    } catch (InputMismatchException ime){
        System.out.println("Your respone must be a whole number");
        sc.next(); // This will advance the reading position
    }
} while (!sc.hasNextInt());
+3

, , ( ), break, :

public static void main(String args[])
{
    System.out.print("Enter the numeral representing your birth month: ");
    do {
        try {
            int month = sc.nextInt();
            break;
        } catch (InputMismatchException ime) {
            System.out.println("Your respone must be a whole number");
            sc.nextLine();
        }
    } while (true);
}

, sc.nextLine() catch, Enter, , nextInt() . nextLine() . .

+2

, try/catch , .

, ( , de-while , , , nullPointer)

    try {
       while (sc != null && !sc.hasNextInt()) {
            month = sc.nextInt();
        } 
    } catch (InputMismatchException ime){
            System.out.println("Your respone must be a whole number");
    }
+2

Make sure you can get an integer first and use regular expressions. Do not use exceptions, if possible, to provide code logic.

int month;
boolean correct = false;
while (!correct && sc.hasNextLine())
{
    String line = sc.nextLine();
    if (!line.matches("^[0-9]+$"))
    {
        System.out.println("Your response must be a whole number");
        correct = false;
    }
    else
    {
        month = Integer.parseInt(line);
        correct = true;
    }
}
+1
source

Source: https://habr.com/ru/post/1530780/


All Articles