Java 将包含元音的字符串替换为“\”

Java 将包含元音的字符串替换为“\”,java,Java,我正试图编写一个程序,打印输入的用户字符串,其中元音替换为u。我在if部分遇到问题,由于编译错误,程序无法打印 导入java.util.Scanner; 公共阶级权力{ 公共静态字符串参数[] { 扫描仪a=新的扫描仪系统.in; System.out.printEnter字符串:; 字符串s=a.nextLine; 整数计数=0; 对于char c:s.toCharArray { 如果c='a'| c='e'| c='i'| c='o'| c='u'{ { c='uu'; System.out

我正试图编写一个程序,打印输入的用户字符串,其中元音替换为u。我在if部分遇到问题,由于编译错误,程序无法打印

导入java.util.Scanner; 公共阶级权力{ 公共静态字符串参数[] { 扫描仪a=新的扫描仪系统.in; System.out.printEnter字符串:; 字符串s=a.nextLine; 整数计数=0; 对于char c:s.toCharArray { 如果c='a'| c='e'| c='i'| c='o'| c='u'{ { c='uu'; System.out.println c[i]; } } System.out.println您的字符串有+计数+大写字母。; } } 应该是

System.out.println(c);

您的代码存在许多问题,无法编译

将c[i]替换为c。c是一个字符,而不是字符串。您甚至没有i。。。 您正在打印计数,但从未增加计数。 即使你要数,你也要数元音,而不是大写字母。 当您将uu分配给c并打印它时,您的输出将始终是uu。 也许你想做这样的事情:

Scanner a = new Scanner (System.in);
System.out.print("Enter string: ");
String s = a.nextLine();
String res = "";
for (char c : s.toCharArray())
{
    if (c=='a' || c=='e' || c=='i' || c=='o' || c=='u') {
        res = res + '_';
    }
    else
        res = res + c;
}
System.out.println(res); //Will contain the string with the vowels replaced with _
或者..更好的代码:

Scanner a = new Scanner (System.in);
System.out.print("Enter string: ");
String s = a.nextLine();
String[] vals = {"a", "u", "o", "e", "i"};
for(String val : vals)
    s = s.replaceAll(val, "_");
System.out.println(s);
首先,需要在第一行java.util.Scanner;前面输入import关键字。 您还需要在下面的代码中删除一个额外的{

if (c=='a' || c=='e' || c=='i' || c=='o' || c=='u') {
{ //<- This is not needed as you have another on on the end of the line above
c = '_';
System.out.println (c[i]);
}
}
此外,上面代码中的c是字符而不是数组,因此您只需调用System.out.println c;但您也只需在调用之前将“u”分配给c,这样您就只能打印出来。另一个问题是,您只需更改由s.ToCharray创建的数组中的值,因此您需要在for循环之前,然后在循环u之后进行此调用使用它创建一个新字符串以分配给s

最后,你们永远不会增加计数,所以你们最后一次打印出来的结果总是0,但我想你们以后会解决这个问题


如果您还没有使用集成开发环境IDE,或者我建议您下载一个IDE,因为它会向您突出显示这些错误,就像文字处理器突出显示拼写和语法错误一样。

您遇到的编译错误是什么?+1,呵呵,我在前2分钟一直在盯着代码看….:p好的地方这可能是一个错误家庭作业/作业,不要认为OP需要正则表达式。但显然是一个很好的解决方案。如果你能解释代码中发生了什么,那就好了。是的,我是数组新手,没有意识到系统。out.printc而不是c[I]。这解决了问题。谢谢!
if (c=='a' || c=='e' || c=='i' || c=='o' || c=='u') {
{ //<- This is not needed as you have another on on the end of the line above
c = '_';
System.out.println (c[i]);
}
}