我正在自学 Java,并使用在线练习进行练习。到目前为止,我只学习了一些方法,因此使用数组进行此练习超出了我的范围,尽管在线的几个解决方案使用数组来完成我想要的操作。
练习是这样的:让用户输入一个带有元音的字符串。只要有元音字母,就将该元音显示为大写字母。
示例:如果用户输入“apples”,则正确的输出是 ApplEs
到目前为止我有这个代码:
import java.util.Scanner;
public class CapitalizeVowels {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string ~ ");
String string = keyboard.nextLine();
for (int i = 0; i < string.length(); i++) {
System.out.print(string.charAt(i));
if (string.charAt(i) == 'a' ||
string.charAt(i) == 'e' ||
string.charAt(i) == 'i' ||
string.charAt(i) == 'o' ||
string.charAt(i) == 'u') {
char upperCaseVowel = Character.toUpperCase(string.charAt(i));
System.out.print(upperCaseVowel);
// need to replace string.charAt(i) with upperCaseVowel
// find something to replace characters
}
}
}
}
例如,当我使用输入字符串“apples”按原样运行代码时,我得到“aAppleEs”作为输出。小写元音和大写元音都被打印。我想我应该用 upperCaseVowel 替换 string.charAt(i) 这是小写元音,但我找不到任何replace()方法或对字符有效果的东西。我尝试了其他东西,如 StringBuilder 等,但我还没有找到一个足够简单的解决方案来避免数组,因为我还没有学习它们。非常感谢任何有关我如何获得正确输出的帮助。谢谢!
最佳答案
你的错误是在测试每个字符是否是元音之前打印它。
相反,在弄清楚每个字符应该是什么之后打印它。循环体应该是:
char next = string.charAt(i);
if (next == 'a' ||
next == 'e' ||
next == 'i' ||
next == 'o' ||
next == 'u') {
next = Character.toUpperCase(next);
}
System.out.print(next);
您可以考虑添加:
else {
next = Character.toLowerCase(next);
}
强制非元音字母小写。
关于Java 用字符替换字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36242818/