为何StringBuilder中指定字符未转换为小写?代码问题排查
Troubleshooting Your Character Lowercase Conversion Issue
Let's walk through why your code isn't converting the specified characters to lowercase as expected—there are two critical bugs in your logic, plus a minor cleanup we can do:
Key Issues in Your Code
- Wrong conversion direction & method misuse
Your goal is to turn target characters lowercase, but you're callingCharacter.toUpperCase()instead ofCharacter.toLowerCase(). That's the exact opposite of what you need! - Invalid parameter for the conversion method
The linesb.setCharAt(i, sb.charAt(Character.toUpperCase(i)))is a major problem. Here,iis the loop's index number (like 0, 1, 2...), not the character you want to modify. Converting this index to an "uppercase character" (which maps to a random Unicode value) and pulling that character from the StringBuilder has nothing to do with your original task. You need to convert the actual character that matched yoursymbolto lowercase.
Minor Cleanup (Not Breaking Functionality)
You're creating a new Scanner instance in both requestString() and requestSymbol(). This isn't causing your conversion failure, but it's unnecessary—you can reuse a single Scanner to avoid redundant resource allocation.
Fixed Code
import java.util.Scanner; public class Task { // Reuse one Scanner instance across the program private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) { StringBuilder sb = new StringBuilder(requestString()); char symbol = requestSymbol().charAt(0); int count = 0; for (int i = 0; i < sb.length(); i++) { if (sb.charAt(i) == symbol) { // Convert the matched character to lowercase and set it back sb.setCharAt(i, Character.toLowerCase(sb.charAt(i))); count++; } } System.out.println("Number of entries: " + count); System.out.println("Converted string: " + sb); scanner.close(); // Clean up the scanner when done } static String requestString() { System.out.println("Enter string:"); return scanner.nextLine(); } static String requestSymbol() { System.out.println("Enter the symbol:"); return scanner.next(); } }
What Changed?
- Swapped
Character.toUpperCase()withCharacter.toLowerCase()to align with your goal of making characters lowercase. - Fixed the conversion parameter—now we're modifying the actual matched character (
sb.charAt(i)) instead of the loop index. - Created a single reusable
Scannerinstance and added aclose()call to clean up resources properly.
内容的提问来源于stack exchange,提问作者dankatle
相关产品推荐
相关产品推荐

