Java中允许用户输入"、'等非标准字符及身高输入实现咨询
Got it, let's break down your two requirements step by step—sounds like you're working on a user input handling feature, so I'll keep this practical with code examples you can test right away.
First off, let's clear up a common confusion: Java doesn't block users from entering " or ' by default. The escape characters (\ before quotes) you might have seen are only for writing string literals in your code—they don't apply to raw user input.
For console input, using Scanner works perfectly to capture these characters. Here's a quick test:
import java.util.Scanner; public class QuotationInputDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Go ahead, type something with \" or ':"); String userInput = scanner.nextLine(); System.out.println("You entered: " + userInput); scanner.close(); } }
Run this, type in something like She yelled "Stop!" and I whispered 'Okay', and it'll print exactly what you entered—no issues.
If you're using a GUI (like Swing's JTextField or JavaFX's TextField), it's even simpler: just call textField.getText() and it'll return the full input including quotes, no extra work needed.
For this, we'll use regex to extract the numbers paired with their respective symbols, then validate and convert them. Based on your description, let's assume " represents feet and ' represents inches (I'll also add support for the more common ' for inches/" for feet format, just in case users mix them up).
Here's a complete, reusable parser:
import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Scanner; public class HeightInputParser { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter height (e.g., 5\"3' for 5ft 3in, or 5'3\"—either works):"); String heightInput = scanner.nextLine().trim(); scanner.close(); Height parsedHeight = parseHeight(heightInput); if (parsedHeight != null) { System.out.printf("Success! Parsed: %d feet, %d inches%n", parsedHeight.feet, parsedHeight.inches); // Optional: Convert to total inches or metric int totalInches = parsedHeight.feet * 12 + parsedHeight.inches; double centimeters = totalInches * 2.54; System.out.printf("Total inches: %d | Centimeters: %.1f%n", totalInches, centimeters); } else { System.out.println("Oops, invalid format. Try something like 6\"1' or 5'9\"."); } } private static Height parseHeight(String input) { // Pattern for your specified format: [feet]"[inches]' (e.g., 5"3') Pattern primaryPattern = Pattern.compile("(\\d+)\")(\\d+)'"); Matcher primaryMatcher = primaryPattern.matcher(input); if (primaryMatcher.find()) { return extractHeightValues(primaryMatcher.group(1), primaryMatcher.group(2)); } // Fallback for common format: [inches]'[feet]" (e.g., 5'3") Pattern fallbackPattern = Pattern.compile("(\\d+)'(\\d+)\")"); Matcher fallbackMatcher = fallbackPattern.matcher(input); if (fallbackMatcher.find()) { // Swap the groups here since inches come first in this format return extractHeightValues(fallbackMatcher.group(2), fallbackMatcher.group(1)); } return null; } private static Height extractHeightValues(String feetStr, String inchesStr) { try { int feet = Integer.parseInt(feetStr); int inches = Integer.parseInt(inchesStr); // Basic validation: inches should be 0-11 (since 12 inches = 1 foot) if (inches >= 0 && inches < 12 && feet >= 0) { return new Height(feet, inches); } else { System.out.println("Invalid values: Feet can't be negative, inches must be 0-11."); return null; } } catch (NumberFormatException e) { System.out.println("Make sure you're using whole numbers for feet and inches."); return null; } } // Helper class to store parsed height data private static class Height { int feet; int inches; Height(int feet, int inches) { this.feet = feet; this.inches = inches; } } }
A few notes on this code:
- It handles both your specified format and the widely used alternative (since users might instinctively type
5'3"instead of5"3'). - It includes basic validation to ensure inches are within a reasonable range (0-11) and feet aren't negative.
- You can easily adjust the regex if you want to allow spaces between numbers and symbols (e.g.,
5" 3'—just add\\s*between the groups, like(\\d+)\")\\s*(\\d+)').
内容的提问来源于stack exchange,提问作者Sophia Green

