Java钢琴和弦输入校验问题:多字符输入未被完整识别
Hey there! I see you're building a Java program to handle piano chords, and you're stuck on parsing inputs like a#m where only the root note is being recognized. Let's break down how to fix this by adding proper multi-character parsing, validation for each character, and lay the groundwork for handling sharps/flats.
The core issue right now is that your current logic probably only checks the first character of the input string, ignoring the rest. We need to handle inputs of different lengths (1, 2, or 3 characters) and validate each position based on allowed characters.
Step 1: Standardize Input First
First, convert the input to a consistent case (like uppercase) to simplify checks—this way you don't have to handle both a and A separately every time.
Step 2: Handle Different Input Lengths
We need to account for 3 possible valid input lengths:
- 1 character: Just a root note (e.g.,
C,G) - 2 characters: Root + sharp/flat, or root + minor (e.g.,
C#,D-,Am) - 3 characters: Root + sharp/flat + minor (e.g.,
A#m,G-m)
Step 3: Validate Each Character
For each position in the input string, we'll check if it's a valid character:
- Position 0 (root note): Must be between
A-G(after standardizing case) - Position 1 (optional): Can be
#(sharp),-(flat), orm(minor) - Position 2 (optional, only for 3-character inputs): Must be
m(and position 1 must be a sharp/flat)
Step 4: Add Sharp/Flat Handling
We'll add variables to track if the chord is sharp, flat, or natural, and another to track if it's minor.
Here's the updated code implementing all these steps:
import java.util.Scanner; public class Hwk9 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a chord (e.g., C, Am, G#m, D-): "); String chordInput = scanner.nextLine().trim().toUpperCase(); // Standardize to uppercase, trim whitespace // Variables to track chord properties char rootNote = ' '; boolean isSharp = false; boolean isFlat = false; boolean isMinor = false; boolean isValid = true; // Check input length first switch (chordInput.length()) { case 1: // Just root note rootNote = chordInput.charAt(0); if (!isValidRootNote(rootNote)) { isValid = false; } break; case 2: rootNote = chordInput.charAt(0); char secondChar = chordInput.charAt(1); if (!isValidRootNote(rootNote)) { isValid = false; break; } // Check if second char is sharp/flat or minor if (secondChar == '#') { isSharp = true; } else if (secondChar == '-') { isFlat = true; } else if (secondChar == 'M') { isMinor = true; } else { isValid = false; } break; case 3: rootNote = chordInput.charAt(0); char modifier = chordInput.charAt(1); char minorMarker = chordInput.charAt(2); if (!isValidRootNote(rootNote)) { isValid = false; break; } // Check modifier is sharp/flat, and third char is 'M' if ((modifier == '#' || modifier == '-') && minorMarker == 'M') { if (modifier == '#') { isSharp = true; } else { isFlat = true; } isMinor = true; } else { isValid = false; } break; default: isValid = false; break; } // Output results or error if (isValid) { System.out.println("Chord parsed successfully!"); System.out.println("Root Note: " + rootNote); System.out.println("Sharp: " + isSharp); System.out.println("Flat: " + isFlat); System.out.println("Minor: " + isMinor); // Add your chord logic here (e.g., generate notes for the chord) } else { System.out.println("Invalid chord input! Please use format like C, Am, G#m, D-."); } scanner.close(); } // Helper method to validate root note private static boolean isValidRootNote(char c) { return c >= 'A' && c <= 'G'; } }
Key Notes About This Code:
toUpperCase()andtrim()clean up user input to avoid case sensitivity and extra whitespace issues.- The
switchstatement organizes logic by input length, making it easy to follow and extend later. - The
isValidRootNotehelper method keeps validation code clean and reusable. - We track all chord properties with clear boolean variables—you can use these to build out the actual chord generation logic later.
- Invalid inputs trigger a clear error message, so users know exactly what format is expected.
内容的提问来源于stack exchange,提问作者David

