例如:输入字符串:aaaaaaaaaa bbbbbbbbbbbbcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
什么字符应该转换成大写?b
输出应该是什么:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a String");
StringBuilder sb = new StringBuilder(keyboard.nextLine());
System.out.println("Which character should be converted to uppercase?");
char c = keyboard.nextLine().charAt(0);
ParsingUtils.changeLetter(sb, c);
System.out.println(sb);
}
public static void changeLetter(StringBuilder sb, char letter)
{
String change = Character.toString(letter); //changes the char in the parameter to string
String change2 = change.toUpperCase(); //make an uppercase copy of the string
char upper = change2.charAt(0); //change the upper case copy to a char
for (int counter = 0; counter < sb.length(); counter++) //Is supposed to replace every instance of the given character with uppercase
{
if (sb.toString().contains(change))
{
sb.setCharAt(counter, upper);
}
}
}
我的代码输出什么:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
有没有一个更好的,不太复杂的方法来做这件事,我太沮丧看到?
我还是一个java新手,所以可能有一个简单的答案完全出乎我的意料。
1条答案
按热度按时间jdzmm42g1#
前三行可以简化为:
使用
charAt(counter)
,而不是检查整个字符串生成器是否包含字母。完整代码: