Problem:
Write a short Java method that counts the number of vowels in a given character
string.
Solution:
package com.basics;
import java.util.Scanner;
public class CountTheNumberOfVowels {
String word = "";
public static void main(String[] args) {
CountTheNumberOfVowels countTheNumberOfVowels = new CountTheNumberOfVowels();
countTheNumberOfVowels.getTheNumber();
System.out.println("the number of vowels in a given character string is: " + countTheNumberOfVowels.countVowels());
}
public void getTheNumber(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter a word");
word = scanner.next();
scanner.close();
}
public int countVowels(){
int numberOfVowels = 0;
char[] characters = word.toLowerCase().toCharArray();
for (int i = 0; i < characters.length; i++) {
if(characters[i] == 'a' || characters[i] == 'e' || characters[i] == 'i' || characters[i] == 'o' || characters[i] == 'u'){
numberOfVowels ++;
}
}
return numberOfVowels;
}
}
Output:
enter a word
Banglore
the number of vowels in a given character string is: 3
Write a short Java method that counts the number of vowels in a given character
string.
Solution:
package com.basics;
import java.util.Scanner;
public class CountTheNumberOfVowels {
String word = "";
public static void main(String[] args) {
CountTheNumberOfVowels countTheNumberOfVowels = new CountTheNumberOfVowels();
countTheNumberOfVowels.getTheNumber();
System.out.println("the number of vowels in a given character string is: " + countTheNumberOfVowels.countVowels());
}
public void getTheNumber(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter a word");
word = scanner.next();
scanner.close();
}
public int countVowels(){
int numberOfVowels = 0;
char[] characters = word.toLowerCase().toCharArray();
for (int i = 0; i < characters.length; i++) {
if(characters[i] == 'a' || characters[i] == 'e' || characters[i] == 'i' || characters[i] == 'o' || characters[i] == 'u'){
numberOfVowels ++;
}
}
return numberOfVowels;
}
}
Output:
enter a word
Banglore
the number of vowels in a given character string is: 3
No comments:
Post a Comment