java - 元音计数器 Java 应用程序:卡在 for 循环中?似乎不是无限循环
问题描述
我制作了一个 java 程序来计算字符串中元音的数量,我需要使用一个或多个 for 循环来为项目执行此操作。问题是在输入字符串后它什么也没做,或者只是花费了太长时间:
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter a string to count the vowels>> ");
String x = s.nextLine();
int numVowels = countVowels(x, "aeiou");
System.out.println(numVowels);
}
static int countVowels(String x, String vowels)
{
int count = 0;
String z = x.toLowerCase();
for (int i = 0; i <= vowels.length() - 1; i++)
{
if (i == vowels.length() - 1)
{
for (int n = z.indexOf(vowels.substring(i)); n != -1; count++)
{
z.replace(vowels.substring(i), "");
}
}
else if (z.indexOf(vowels.substring(i, i + 1)) != -1)
{
for (int n = z.indexOf(vowels.substring(i, i + 1)); n != -1; count++)
{
z.replace(vowels.substring(i, i + 1), "");
}
}
}
return count;
}
}
我减少了循环的数量,因为原来的很混乱。我认为问题出在嵌套循环上,但我还没有尝试在本地编译器上运行它,只有在线 IDE。我听说它对编译时间产生了很大的影响。
解决方案
这是一个无限循环:z
如果只使用z.replace
. 由于字符串在 Java 中是不可变的,因此不能仅通过调用方法来更改它,必须重新赋值:
z = z.replace(...)
推荐阅读
- java - Eclipse 上单独文件中的 Java 文档
- javascript - 使用 jQuery 的 .clone() 保留复选框 onclick 功能
- html - 如何将自定义 HTML 添加到 wordpress 中的特定页面?
- spring-boot - Set active spring profile with bootWar
- python - Link 2 values of of different result
- floating-point - Precision of the quotient of two double precision numbers
- java - 使用 apache CXF 使用 equals/hashCode 方法从 WSDL 生成 POJO
- steam-web-api - Saving steam session for a long time
- r - 尽管使用 bigmatrix 并且只发送描述符,为什么我的工作人员开始我的大矩阵乘法需要这么长时间?
- c++ - Cucumber-cpp required software for running example