首页 > 解决方案 > 元音计数器 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。我听说它对编译时间产生了很大的影响。

标签: javaperformancefor-loop

解决方案


这是一个无限循环:z如果只使用z.replace. 由于字符串在 Java 中是不可变的,因此不能仅通过调用方法来更改它,必须重新赋值:

z = z.replace(...)

推荐阅读