Andre Dorsey
Andre Dorsey

Reputation: 19

while Loop for vowel counter

I am trying to get a while loop program where it counts the number of vowels and takes the vowels out of the sentences, also repeating the process until the user inputs quit. I am having trouble getting the while loop to work.

import java.util.Scanner;
public class blank1
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a Sentence: (Enter quit to exit) ");
        String input1 = input.nextLine();
        int vowelCount = 0;

        while(input.equals("quit")){

            System.out.println("Enter a Sentence: (Enter quit to exit) ");
            for (char c : input1.toCharArray())
            {
                switch(c)
                {

                    case 'A':
                    case 'a':

                    case 'E':
                    case 'e':

                    case 'I':
                    case 'i':

                    case 'O':
                    case 'o':

                    case 'U':
                    case 'u':
                        vowelCount++;

                        System.out.println(vowelCount);
                }
            }
        }
    }
}

Upvotes: 1

Views: 1840

Answers (3)

Andreas
Andreas

Reputation: 159135

You need to:

  • Add a not operator: while (! input.equals("quit")) {
  • Move the println(vowelCount) after the loop
  • Move the second println("Enter ...") after that
  • Add a input1 = input.nextLine() after that
  • Do vowelCount = 0 right inside the loop

To not do the print + nextLine in two places, try this instead:

Scanner input = new Scanner(System.in);
while (true) {
    System.out.println("Enter a sentence: (Enter quit to exit) ");
    String text = input.nextLine();
    if (text.equals("quit"))
        break;
    int vowelCount = 0;
    for (char c : text.toCharArray())
        switch (c) {
            case 'A': case 'a':
            case 'E': case 'e':
            case 'I': case 'i':
            case 'O': case 'o':
            case 'U': case 'u':
                vowelCount++;
        }
    System.out.println("Found " + vowelCount + " vowels");
}

Upvotes: 1

CodeRunner
CodeRunner

Reputation: 687

Change the signature of the while loop

from

while(input.equals("quit"))

to

while( ! input.equals("quit"))

Upvotes: 0

StillLearnin
StillLearnin

Reputation: 1499

You are looping while input equals "quit". Instead, you want to loop while input does not equal "quit".

Upvotes: 0

Related Questions