You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何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 calling Character.toUpperCase() instead of Character.toLowerCase(). That's the exact opposite of what you need!
  • Invalid parameter for the conversion method
    The line sb.setCharAt(i, sb.charAt(Character.toUpperCase(i))) is a major problem. Here, i is 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 your symbol to 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?

  1. Swapped Character.toUpperCase() with Character.toLowerCase() to align with your goal of making characters lowercase.
  2. Fixed the conversion parameter—now we're modifying the actual matched character (sb.charAt(i)) instead of the loop index.
  3. Created a single reusable Scanner instance and added a close() call to clean up resources properly.

内容的提问来源于stack exchange,提问作者dankatle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 20:42:43