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

Java菜单驱动程序开发:switch嵌套if-else写法及执行异常排查求助

Hey there! Let's tackle your two Java menu-driven program questions step by step.

1. Fixing the "No Case Executes After Input" Issue

It’s super frustrating when you enter a menu option and nothing happens—let’s go through the most common causes and fixes:

  • Case Sensitivity Mismatch
    This is the #1 culprit! If your menu asks for "A" but you input "a" (or vice versa), your case 'A': won’t trigger. Fix this by standardizing the input’s case before passing it to the switch:

    // Convert input to uppercase (or lowercase) to eliminate case issues
    char choice = scanner.next().toUpperCase().charAt(0);
    
  • Scanner Buffer Glitches
    If you used nextInt() or nextDouble() before reading the menu choice, the leftover newline character can cause nextLine() to read an empty string. To fix this:

    • Either use next() instead of nextLine() to grab the menu option (it skips whitespace automatically), or
    • Add a dummy scanner.nextLine() after numeric inputs to clear the buffer.
  • Wrong Switch Expression Type
    Double-check that your switch variable matches the case values. For example:

    • If you’re using string inputs like "A", your switch should use a String variable, not a char.
    • If you’re using chars, make sure your cases use single quotes ('A') instead of double quotes ("A").
  • Add a Default Case
    Even if it’s not the root cause, a default: case will help you confirm if the input is being read at all. It can print an error like "Invalid choice—please try again."

Here’s a corrected snippet with these fixes:

import java.util.Scanner;

public class AttendanceCostCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        char choice;

        do {
            // Menu display
            System.out.println("\n=== University Attendance Cost Calculator ===");
            System.out.println("A. Undergraduate Student");
            System.out.println("B. Graduate Student");
            System.out.println("C. International Student");
            System.out.println("Q. Exit");
            System.out.print("Enter your choice: ");

            // Standardize input to uppercase
            choice = scanner.next().toUpperCase().charAt(0);

            switch (choice) {
                case 'A':
                    System.out.println("Calculating Undergraduate costs...");
                    // Add your logic here
                    break;
                case 'B':
                    System.out.println("Calculating Graduate costs...");
                    // Add your logic here
                    break;
                case 'C':
                    System.out.println("Calculating International Student costs...");
                    // Add your logic here
                    break;
                case 'Q':
                    System.out.println("Exiting program. Goodbye!");
                    break;
                default:
                    System.out.println("Oops! That's not a valid option. Try A, B, C, or Q.");
            }
        } while (choice != 'Q');

        scanner.close();
    }
}

2. Embedding if-else Inside Switch Cases

Adding if-else logic inside a switch case is straightforward—you just write the conditional code directly within the case block. This is perfect for handling sub-categories, like different credit loads or residency statuses for the same student type.

Here’s an example where we calculate undergraduate costs based on credit hours:

case 'A':
    System.out.print("Enter number of credit hours: ");
    int credits = scanner.nextInt();
    double totalCost;

    // Use if-else to handle different credit tiers
    if (credits <= 12) {
        totalCost = 4500.00; // Flat rate for full-time (12 credits or less)
    } else if (credits > 12 && credits <= 18) {
        totalCost = 4500.00 + (credits - 12) * 350.00; // Extra credits cost $350 each
    } else {
        totalCost = 4500.00 + (6 * 350.00) + (credits - 18) * 300.00; // Discount for over 18 credits
    }

    System.out.printf("Total attendance cost: $%.2f%n", totalCost);
    break;

You can nest as many if-else blocks as needed inside any case—just make sure to keep the code organized so it’s easy to read later.

内容的提问来源于stack exchange,提问作者SNepo01

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:06:52