checking if input from scanner is int with while loop java

前端 未结 3 1345
既然无缘
既然无缘 2021-01-17 08:01

I basically want the following while loop to check if the input is an integer. It cannot contain decimals because it is pointing to an array. If the value entered is a decim

3条回答
  •  被撕碎了的回忆
    2021-01-17 08:41

    Check that the input is integer with hasNextInt() before you call nextInt(). Otherwise nextInt() throws an InputMismatchException when user types a non integer.

    int monthInput;
    
    System.out.print("Enter month (valid values are from 1 to 12): ");
    Scanner monthScan = new Scanner(System.in);
    
    if (monthScan.hasNextInt()) {
        monthInput = monthScan.nextInt();
    } else {
        monthScan.next();   // get the inputted non integer from scanner
        monthInput = 0;
    }
    
    // If the month input is below 1 or greater than 12, prompt for another value
    while (monthInput < 1 || monthInput > 12) {
        System.out.print("Invalid value! Enter month (valid values are from 1 to 12): ");
        if (monthScan.hasNextInt()) {
            monthInput = monthScan.nextInt();
         } else {
           String dummy = monthScan.next();
           monthInput = 0;
        }
    }
    

提交回复
热议问题