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. I have an error on my else statement but I'm not quite sure what I am missing. Is my code correct to print out a character counter? Something is wrong with my else statement. Do I need to remove or add anything?
import java.util.Scanner;
public class Frosty
{
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;
System.out.print("Enter a sentence or phrase: ");
phrase = scan.nextLine();
if (phrase.equalsIgnoreCase("quit"));
{
}
else {
length = phrase.length();
}
}
// 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();
}
while (!phrase.equalsIgnoreCase("quit"));
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
