Home > Software design >  Vowel counter Java application: stuck in for loops? Doesn't seem to be an infinite loop
Vowel counter Java application: stuck in for loops? Doesn't seem to be an infinite loop

Time:10-28

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.

CodePudding user response:

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(...)

CodePudding user response:

I took the liberty of using while-loop instead of for-loop since the idea is to keep looping till find, count and replace all the vowels one by one.

static int countVowels(String x, String vowels)
{
    int count = 0;
    String z = x.toLowerCase();
    for (int i = 0; i <= vowels.length() - 1; i  )
    {
        String vowel = Character.toString(vowels.charAt(i));
        while (z.indexOf(vowel) != -1){
            count  ;
            z = z.replaceFirst(vowel, "");
        }
    }
    return count;
}
  • Related