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), yourcase '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 usednextInt()ornextDouble()before reading the menu choice, the leftover newline character can causenextLine()to read an empty string. To fix this:- Either use
next()instead ofnextLine()to grab the menu option (it skips whitespace automatically), or - Add a dummy
scanner.nextLine()after numeric inputs to clear the buffer.
- Either use
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 aStringvariable, not achar. - If you’re using chars, make sure your cases use single quotes (
'A') instead of double quotes ("A").
- If you’re using string inputs like
Add a Default Case
Even if it’s not the root cause, adefault: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

