Java手机号字母转数字及按规则添加连字符问题求助
Solution for Formatting Phone Number Digits
Got it, let's fix this problem step by step. The main issue with your current code is that it only adds a hyphen after the first 3 digits, but doesn't handle the subsequent groups of 4 digits. Also, we need to avoid adding an extra hyphen at the end of the formatted string. Here's the revised code with clear explanations:
import java.util.Scanner; public class question1 { public static void main(String[] args) { boolean notLetter = false; Scanner console = new Scanner(System.in); StringBuilder digitsBuilder = new StringBuilder(); // Use StringBuilder for better performance System.out.print("Enter a phone number in letters only: "); String phoneNumber = console.nextLine(); String cleanedInput = phoneNumber.replaceAll(" ", ""); // Remove all spaces // Step 1: Convert letters to digits for (int i = 0; i < cleanedInput.length(); i++) { char c = cleanedInput.charAt(i); if (!Character.isLetter(c)) { notLetter = true; break; } char upperC = Character.toUpperCase(c); switch (upperC) { case 'A': case 'B': case 'C': digitsBuilder.append('2'); break; case 'D': case 'E': case 'F': digitsBuilder.append('3'); break; case 'G': case 'H': case 'I': digitsBuilder.append('4'); break; case 'J': case 'K': case 'L': digitsBuilder.append('5'); break; case 'M': case 'N': case 'O': digitsBuilder.append('6'); break; case 'P': case 'Q': case 'R': case 'S': digitsBuilder.append('7'); break; case 'T': case 'U': case 'V': digitsBuilder.append('8'); break; case 'W': case 'X': case 'Y': case 'Z': digitsBuilder.append('9'); break; } } if (notLetter) { System.out.println("Please indicate only alphabets"); return; // Exit early if input is invalid } String digits = digitsBuilder.toString(); if (digits.isEmpty()) { System.out.println("No valid characters entered"); return; } // Step 2: Format the digits with hyphens StringBuilder formattedNumber = new StringBuilder(); int position = 0; // Add the first group of 3 digits int firstGroupEnd = Math.min(position + 3, digits.length()); formattedNumber.append(digits.substring(position, firstGroupEnd)); position = firstGroupEnd; // Add remaining groups of 4 digits, with hyphens before each group while (position < digits.length()) { formattedNumber.append('-'); int nextGroupEnd = Math.min(position + 4, digits.length()); formattedNumber.append(digits.substring(position, nextGroupEnd)); position = nextGroupEnd; } // Output the result System.out.println(formattedNumber.toString()); } }
Key Changes & Explanations:
- Used
StringBuilderinstead ofStringconcatenation: String concatenation creates a new String object each time, which is inefficient for repeated operations.StringBuilderis designed for mutable string building and performs better here. - Separated conversion and formatting logic: Splitting the code into two clear steps (convert letters to digits first, then format) makes it easier to debug and maintain.
- First group handling: We take the first 3 digits (or fewer if the input is shorter than 3) and add them to the formatted string.
- Subsequent groups handling: After the first 3 digits, we add a hyphen before each subsequent group of up to 4 digits. This ensures we don't get an extra hyphen at the end, since we only add a hyphen if there are more digits to process.
- Early exit for invalid input: Added checks to exit early if the input has non-letter characters or is empty, making the code cleaner.
Example Outputs:
- Input:
ABCDEFGHIJK→ Output:222-3333-444 - Input:
ABCDE→ Output:222-33 - Input:
ABCDEFG→ Output:222-3333 - Input:
A→ Output:2
内容的提问来源于stack exchange,提问作者Janice Teng
相关产品推荐
相关产品推荐

