Question: I need help with my code. I need my program to character count and then terminate when the user enters quit. My character counter counts
I need help with my code. I need my program to character count and then terminate when the user enters "quit." My character counter counts all the a, e, s, and t in my code and blank space. It runs good with no errors But for some reason I have an infinite loop and need help to make my while loop false so it terminates my code and doesn't infinitely continue.
import java.util.Scanner;
public class Count
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String phrase; // a string of characters
int countBlank = 0; // the number of blank spaces in the phrase
int countA; // number of A's in the phrase
int countE; // number of E's in the phrase
int countS; // number of S's in the phrase
int countT; // number of T's in the phrase
int length; // the length of the phrase
char ch; // an individual character in the string
// print a program header
System.out.println();
System.out.println("Character Counter");
System.out.println();
// Read in a string and find its length
System.out.print("Enter a sentence or phrase: ");
phrase = scan.nextLine();
length = phrase.length();
while (!phrase.equalsIgnoreCase("quit") ) // while not equal to quit
{
// Initialize counts
countBlank = 0;
countA = 0;
countE = 0;
countS = 0;
countT = 0;
// Print the results
System.out.println();
System.out.println("Number of blank space: ");
System.out.println();
// a for loop to go through the string character by character
// and count the blank spaces
for (int i = 0; i < length; i++)
{
// get the character off the string
ch = phrase.charAt(i);
switch (ch)
{
case ' ':
countBlank++;
break;
case 'a':
case 'A':
countA++;
break;
case 'e':
case 'E':
countE++;
break;
case 's':
case 'S':
countS++;
break;
case 't':
case 'T':
countT++;
break;
}
}
// Print the results
System.out.println();
System.out.println("Number of blank spaces: " + countBlank);
System.out.println("Number of A's: " + countA);
System.out.println("Number of E's: " + countE);
System.out.println("Number of S's: " + countS);
System.out.println("Number of T's: " + countT);
System.out.println();
}
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
