assignment4
This commit is contained in:
86
labs/lab5/FOR LOOP & SWITCH-CASE.txt
Normal file
86
labs/lab5/FOR LOOP & SWITCH-CASE.txt
Normal file
@ -0,0 +1,86 @@
|
||||
//FOR LOOP & SWITCH-CASE
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Count
|
||||
{
|
||||
public static void main (String[] args)
|
||||
{
|
||||
String phrase; // a string of characters
|
||||
int countBlank; // the number of blanks (spaces) in the phrase
|
||||
int countA; // the number of 'a' and 'A'
|
||||
int countE; // the number of 'e' and 'E'
|
||||
int countS; // the number of 's' and 'S'
|
||||
int countT; // the number of 't' and 'T'
|
||||
int length; // the length of the phrase
|
||||
char ch; // an individual character in the string
|
||||
Scanner scan = new Scanner(System.in);
|
||||
|
||||
// Print a program header
|
||||
System.out.println ();
|
||||
System.out.println("Character Counter");
|
||||
System.out.println();
|
||||
|
||||
// Outer while loop to keep asking for phrases until "quit"
|
||||
while (true) {
|
||||
System.out.print("Enter a sentence or phrase (or type 'quit' to exit): ");
|
||||
phrase = scan.nextLine();
|
||||
|
||||
// Exit if user types "quit"
|
||||
if (phrase.equalsIgnoreCase("quit")) { // Capital-lower letter ignore
|
||||
break;
|
||||
}
|
||||
|
||||
// Initialize counts for each new phrase
|
||||
countBlank = 0;
|
||||
countA = 0;
|
||||
countE = 0;
|
||||
countS = 0;
|
||||
countT = 0;
|
||||
|
||||
// Get the length of the phrase
|
||||
length = phrase.length();
|
||||
|
||||
// Loop through each character in the phrase
|
||||
for (int i = 0; i < length; i++) {
|
||||
ch = phrase.charAt(i); // get character at position i
|
||||
|
||||
// Use switch statement to count occurrences of specific characters
|
||||
switch (ch) {
|
||||
case 'a':
|
||||
case 'A':
|
||||
countA++;
|
||||
break;
|
||||
case 'e':
|
||||
case 'E':
|
||||
countE++;
|
||||
break;
|
||||
case 's':
|
||||
case 'S':
|
||||
countS++;
|
||||
break;
|
||||
case 't':
|
||||
case 'T':
|
||||
countT++;
|
||||
break;
|
||||
case ' ':
|
||||
countBlank++; // count spaces
|
||||
break;
|
||||
default:
|
||||
// Do nothing for other characters
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Print the results
|
||||
System.out.println();
|
||||
System.out.println("Number of blank spaces: " + countBlank);
|
||||
System.out.println("Number of 'a'/'A': " + countA);
|
||||
System.out.println("Number of 'e'/'E': " + countE);
|
||||
System.out.println("Number of 's'/'S': " + countS);
|
||||
System.out.println("Number of 't'/'T': " + countT);
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
System.out.println("Goodbye!"); // Print a goodbye message when exiting
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user