You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 Scanner objects 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 calling nextDouble() right after prompting the user, which immediately consumes the input value. Later, when you check hasNextDouble() and call nextDouble() 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 InputMismatchException occurs 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 Scanner to handle all input, eliminating buffering conflicts.
  • Exception Catching: Each input step is wrapped in a try-catch block to immediately catch InputMismatchException when the user enters invalid data. We clear the input buffer with scanner.nextLine() to prevent leftover invalid input from disrupting subsequent operations.
  • Store Values in Variables: Valid double values are saved to variables (iq and termMean), 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:58:45