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

huangapple go评论81阅读模式
英文:

Why character in StringBuild does not change?

问题

字符必须从控制台输入以在此行更改为小写字母但它显示相同的单词符号不会改变

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, Character.toLowerCase(sb.charAt(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();
    }
}
英文:

The character must be entered from the console to change to lowercase letters on this line. But it displays the same word and the symbol does not change.

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 &lt; sb.length(); i++) {
            if (sb.charAt(i) == symbol) {
                sb.setCharAt(i, sb.charAt(Character.toUpperCase(i)));
                count++;
            }
        }
        System.out.println(&quot;Number of entries: &quot; + count);
        System.out.println(&quot;Converted string: &quot; + sb);
    }
    
    static String requestString() {
        Scanner scanner = new Scanner(System.in);
        System.out.println(&quot;Enter string:&quot;);
        return scanner.nextLine();
    }
    
    static String requestSymbol() {
        Scanner scanner = new Scanner(System.in);
        System.out.println(&quot;Enter the symbol:&quot;);
        return scanner.next();
    }
}

答案1

得分: 3

似乎是这一行出了问题:

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

应该改为:

sb.setCharAt(i, Character.toUpperCase(symbol));
英文:

It seems to be a problem with the line:

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

It should be:

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

huangapple
  • 本文由 发表于 2020年5月30日 11:39:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/62097495.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定