为什么StringBuilder中的字符没有改变?

3

在此行中,必须从控制台输入字符才能转换为小写字母。但它显示相同的单词,符号不会改变。

public class Task {
    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) {
                sb.setCharAt(i, sb.charAt(Character.toUpperCase(i)));
                count++;
            }
        }
        System.out.println("Number of entries: " + count);
        System.out.println("Converted string: " + sb);
    }

    static String requestString() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter string:");
        return scanner.nextLine();
    }

    static String requestSymbol() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the symbol:");
        return scanner.next();
    }
}
1个回答

3

这似乎是一条有问题的代码行:

sb.setCharAt(i, sb.charAt(Character.toUpperCase(i)));

应该是:
sb.setCharAt(i, Character.toUpperCase(symbol));

转换为小写字母 - Elliott Frisch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接