Java -Vowels and Consonants - Write a class with a constructor that accepts a St
ID: 3545868 • Letter: J
Question
Java -Vowels and Consonants - Write a class with a constructor that accepts a String object as its argument. The class should have a method that returns the number of vowels in the string, and another method that returns the number of consonants in the string. Demonstrate the class in a program that performs the following steps: 1. The user is asked to enter a string. 2. The program displays the following menu: a. Count the number of vowels in the string b. Count the number of consonants in the string c. Count both the vowels and consonants in the string d. Enter another string e. Exit the program 3. The program performs the operation selected by the user and repeats until the user selects e, to exit the program.
Explanation / Answer
please rate
import java.util.Scanner;
// Class that will contain the required methods
public class VowelsConsonant {
String word;
// Constructor to get the input
public VowelsConsonant(String word){
this.word = word.toLowerCase();
}
// Method to count number of vowels
public int getNumberOfVowels(){
int vowels = 0;
for(int i=0;i<word.length();i++){
if (word.charAt(i)=='a'||word.charAt(i)=='e'||word.charAt(i)=='i'||word.charAt(i)=='o'||word.charAt(i)=='u'){
vowels ++;
}
}
return vowels;
}
public int getNumberOfConosnants(){
int consonants = 0;
for(int i=0;i<word.length();i++){
if (!(word.charAt(i)=='a'||word.charAt(i)=='e'||word.charAt(i)=='i'||word.charAt(i)=='o'||word.charAt(i)=='u')){
consonants ++;
}
}
return consonants;
}
public static void main(String[] args){
System.out.println("Enter a string: ");
Scanner input = new Scanner(System.in);
String word = input.next();
VowelsConsonant vc = new VowelsConsonant(word);
while(true){
System.out.println(
"a. Count the number of vowels in the string " +
"b. Count the number of consonants in the string " +
"c. Count both the vowels and consonants in the string " +
"d. Enter another string "+
"e. Exit the program "+
"Enter your choice"
);
char choice = input.next().toLowerCase().charAt(0);
switch(choice){
case 'a':
System.out.println("Number of vowels: "+vc.getNumberOfVowels());
break;
case 'b':
System.out.println("Number of consonants: "+vc.getNumberOfConosnants());
break;
case 'c':
System.out.println("Number of vowels: "+vc.getNumberOfVowels());
System.out.println("Number of consonants: "+vc.getNumberOfConosnants());
break;
case 'd':
System.out.println("Enter a word: ");
word = input.next();
vc = new VowelsConsonant(word);
break;
case 'e':
System.out.println("Program completed");
System.exit(0);
default:
System.out.println("Invalid choice");
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.