AFanmhi
AFanmhi

Reputation: 33

Java Error when text input instead of number

I am just trying to get code to work where the code asks again for an answer, if text or a symbol is entered, instead of a required integer:

import java.util.Scanner;

class timecalc {

int hrs = 0;
int min = 0;
static int hourflag = 0;
static int minflag = 0;
Scanner sc = new Scanner(System.in);

public int getHours() {

    try {
        hourflag = hourflag + 1;
        if (hourflag > 1) {
            System.out.println("Invalid month Please enter hours again:");
        }
        System.out.println("Enter month:");
        return hrs = sc.nextInt();

    } catch (InputMisMAtchException e) {
        System.out.println("entered invalid input " + e);
    }
}

Have reviewed answers already given but cant get a workable solution

Any ideas?

Upvotes: 1

Views: 401

Answers (1)

Nicholas K
Nicholas K

Reputation: 15423

I won't give you the entire code, but just a hint or psuedo-code. As an exercise you can implement it as per your requirement.

System.out.println("Enter month:");
while (true) {
    try {
        int min = sc.nextInt();
        break;
    } catch (InputMismatchException ex) {
        System.err.println("Invalid input, please enter again");
        sc.nextLine();  //  <----- advance the scanner
    }
}

Here the logic is to loop until we get the right input. If it is an invalid input, the loop never breaks.

Also as a side-note, I would recommend you to create just one method to fetch correct inputs and call it respectively from other methods. Rather than duplicating this logic everywhere.

Upvotes: 1

Related Questions