我正在自学Java并练习使用在线练习。我只学到了直到迄今为止使用数组进行此练习的方法超出我的范围,即使在线使用几个解决方案使用数组来做我想做的事情。Java用字符替换字符
练习是这样的:让用户用元音输入一个字符串。无论哪里出现元音字母,都会将该元音显示为大写字母。
例如:如果用户输入“苹果”,正确的输出是苹果
我到目前为止这样的代码:
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
}
}
}
}
当我运行我的代码,因为它是与输入字符串“苹果”,例如,我得到“aAppleEs”作为我的输出。正在打印小写元音和大写元音。我想我应该用upperCaseVowel来代替string.charAt(i),它是小写的元音,但是我找不到任何replace()方法或者某种特殊效果。我尝试了其他的东西,比如StringBuilder等,但是我还没有遇到一个简单的解决方案,以避免数组,因为我还没有学习它们。任何帮助我如何能得到正确的输出是高度赞赏。谢谢!
[There's a replace method](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace%28char,%20char%29)。 – resueman
不要在$ i^{th} $位置打印字符,直到检查它是否为元音。 – user2505282