Skip to content
Advertisement

Vowel counter Java application: stuck in for loops? Doesn’t seem to be an infinite loop

I made a java program to count the number of vowels in a string, and I need to use a, or multiple, for loop(s) to do it for a project. The problem is that it does not do anything, or just takes too long, after inputting the string:

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;
  }
}

I have reduced the number of loops, because the original was very confusing. I think the problem is with the nested loops, but I have not yet tried running this on a local compiler, only online IDEs. I’ve heard that it makes a world of difference for compile times.

Advertisement

Answer

It’s an infinite loop: you’re not doing anything with z if you use only z.replace. Since strings are immutable in Java, you can’t change it by only calling a method, you must assign it again:

z = z.replace(...)
10 People found this is helpful
Advertisement