Scanner输入if/else失效及InputMismatchException异常处理问题
Fixing InputMismatchException & Logical Issues in Your Java Scanner Code
Hey there! Let's break down the problems in your code and get it working as expected.
Key Problems in Your Current Code
- Unnecessary Multiple Scanner Instances: You don't need two
Scannerobjects for reading from the same input stream (System.in). Using multiple scanners can cause unexpected buffering behavior and input conflicts. - Misused
nextDouble()Calls: You're callingnextDouble()right after prompting the user, which immediately consumes the input value. Later, when you checkhasNextDouble()and callnextDouble()again in the if/else blocks, the scanner is waiting for new input instead of using the values the user already entered. - Missing Exception Handling: The
InputMismatchExceptionoccurs because you're not catching errors when the user enters non-double values. Your else block won't trigger here because the exception is thrown before the code reaches that check.
Corrected Code with Exception Handling
import java.util.InputMismatchException; import java.util.Scanner; public class NestedIf { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Double iq = null; Double termMean = null; // Handle IQ input with exception checking System.out.println("Please enter your IQ: "); try { iq = scanner.nextDouble(); } catch (InputMismatchException e) { System.out.println("Please enter the right format"); scanner.nextLine(); // Clear invalid input from buffer to avoid future issues return; // Exit program since input is invalid } // Handle term mean input with exception checking System.out.println("Please enter your term mean: "); try { termMean = scanner.nextDouble(); } catch (InputMismatchException e) { System.out.println("Please enter the right format"); scanner.nextLine(); // Clear invalid input from buffer return; // Exit program since input is invalid } // Evaluate valid input values if (iq > 110 && termMean > 18) { System.out.println("You got 30 percent discount."); } else if (iq > 100 && termMean > 17) { System.out.println("You got 20 percent discount."); } else if (iq < 100 && termMean < 17) { System.out.println("You have no discount"); } else { // Cover edge cases not caught by previous conditions System.out.println("You have no discount"); } scanner.close(); } }
Explanation of the Fixes
- Single Scanner Instance: We use one
Scannerto handle all input, eliminating buffering conflicts. - Exception Catching: Each input step is wrapped in a
try-catchblock to immediately catchInputMismatchExceptionwhen the user enters invalid data. We clear the input buffer withscanner.nextLine()to prevent leftover invalid input from disrupting subsequent operations. - Store Values in Variables: Valid double values are saved to variables (
iqandtermMean), so we can reuse them in the if/else checks without re-reading input. - Complete Condition Coverage: Added an else block to cover scenarios that don't fit the initial if/else if conditions (like IQ >100 but term mean ≤17, etc.).
内容的提问来源于stack exchange,提问作者Neamat Tabani
相关产品推荐
相关产品推荐

