Skip to content
Advertisement

For loop is printing out multiple print statements

I’m making a program for class which prints out the number of vowels in a word and any help would be appreciated. Currently, the program prints out the correct number of vowels but also prints out the print statement, “vowels:” multiple times before. I’ve tried moving the print statement and the braces around but it says “error: ‘else if’ without ‘if'”. I’m completely new to Java so sorry if the solution is in plain sight. Thank you in advance 🙂

      import java.util.Scanner;
         public class Main
        {
             public static void main(String[] args) {
                Scanner input = new Scanner(System.in);
                System.out.print("Enter text: ");
                String text = input.nextLine();
                text = text.toLowerCase();
                int vowels= 0;
                int l;
                l= text.length();

               for (int i = 1; i < text.length(); i++) { 
                 String wordPRT = text.substring(i,i+1);
                  if (wordPRT.compareToIgnoreCase("a")==0 || wordPRT.compareToIgnoreCase("e")==0|| 
                     wordPRT.compareToIgnoreCase("i")==0
                      || wordPRT.compareToIgnoreCase("o")==0
                      || wordPRT.compareToIgnoreCase("u")==0){
                         vowels++;

                    System.out.println("vowels: " + vowels);
                 }
                 else if(vowels<1){

               System.out.print("no vowels");

                }
              }
             }
            }









Advertisement

Answer

Move the print statements out of the for loop.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter text: ");
        String text = input.nextLine();
        text = text.toLowerCase();
        int vowels = 0;
        int l;
        l = text.length();

        for (int i = 1; i < text.length(); i++) {
            String wordPRT = text.substring(i, i + 1);
            if (wordPRT.compareToIgnoreCase("a") == 0 || wordPRT.compareToIgnoreCase("e") == 0
                    || wordPRT.compareToIgnoreCase("i") == 0 || wordPRT.compareToIgnoreCase("o") == 0
                    || wordPRT.compareToIgnoreCase("u") == 0) {
                vowels++;    
            }
        }
        if (vowels >= 1) {
            System.out.println("vowels: " + vowels);
        } else {
            System.out.print("no vowels");
        }
    }
}

A sample run:

Enter text: Hello
vowels: 2
Advertisement