修复Java getLineNumberFor方法:按姓氏首字符返回对应排队编号
Fixing the
getLineNumberFor Method in ConferenceRegistration Let's break down the issues in your current code and fix them step by step to meet the requirement:
Issues with the Current Code
- Unnecessary Scanner Usage: The method already receives
lastNameas a parameter, so creating aScannerto read input inside the method is redundant and overwrites the passed-in value entirely. - Invalid Comparison Logic: You're comparing the entire
StringlastNameto achar('m'), which isn't valid in Java. Even if you used theguesscharacter you extracted, the logic is reversed—you're returning line 1 for characters >= 'm', but the requirement says line 1 is for A-M. - Case Sensitivity: The code doesn't handle lowercase letters (e.g., a last name starting with 'a' would incorrectly go to line 2).
Corrected Code
public class ConferenceRegistration { /** * Assists in guiding people to the proper line based on their last name. * * @param lastName The person's last name * @return The line number based on the first letter of lastName */ public int getLineNumberFor(String lastName) { // Handle edge cases: null or empty last name if (lastName == null || lastName.isBlank()) { throw new IllegalArgumentException("Last name cannot be null or empty"); } // Get first character, convert to uppercase to handle case insensitivity char firstChar = lastName.toUpperCase().charAt(0); // Apply the line assignment logic if (firstChar >= 'A' && firstChar <= 'M') { return 1; } else if (firstChar >= 'N' && firstChar <= 'Z') { return 2; } else { // Handle non-alphabetic starting characters (optional but robust) throw new IllegalArgumentException("Last name must start with an alphabetic character"); } } // Optional: Main method to test the functionality public static void main(String[] args) { ConferenceRegistration reg = new ConferenceRegistration(); java.util.Scanner scanner = new java.util.Scanner(System.in); System.out.print("Enter your last name: "); String lastName = scanner.nextLine(); try { int line = reg.getLineNumberFor(lastName); System.out.println("Please proceed to line " + line); } catch (IllegalArgumentException e) { System.out.println("Error: " + e.getMessage()); } scanner.close(); } }
Key Fixes Explained
- Removed Redundant Scanner: We now use the
lastNameparameter directly instead of reading new input, which is what the method is designed to do. - Case Insensitivity: Converting the first character to uppercase ensures both 'a'-'m' and 'A'-'M' are correctly mapped to line 1.
- Correct Range Check: We explicitly check if the first character falls within 'A'-'M' (return 1) or 'N'-'Z' (return 2), which perfectly aligns with your requirement.
- Input Validation: Added checks for null/empty last names and non-alphabetic starting characters to make the method more robust and user-friendly.
内容的提问来源于stack exchange,提问作者Joshua Thao
相关产品推荐
相关产品推荐

