Find number of vowels and digits in a String using Java:
In this tutorial, we will learn how to calculate the total number of vowels and digits in a String .
-
We are using the Scanner class to get the input from the user. Initialise two counter variables to store the count of vowels and digits in the string.
-
Then using a for loop, we will check each character of that string.
-
Using a if condition, we will check if the current iterating character is equal to any vowel.
-
Both lower case and upper case vowels, i.e. ’AEIOU’ and ’aeiou’ should be considered while checking.
-
If the character is vowel, increment the counter for vowel by 1.
-
If the character is not vowel, check if it is a digit using Character.isDigit() method.
-
If it is a digit, increment the counter for digit by 1.
-
After the loop is completed, print both counters.
Program :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String inputStr;
int v = 0;
int n = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your string : ");
inputStr = scanner.nextLine();
for (int i = 0; i < inputStr.length(); i++) {
char c = inputStr.charAt(i);
if (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' || c == 'a' || c == 'e' || c == 'i' || c ==
'o' || c == 'u') {
v++;
} else if (Character.isDigit(c)) {
n++;
}
}
System.out.println("No of vowels " + v);
System.out.println("No of numbers " + n);
}
}
It will give output as like below:
Enter your string :
hello123
No of vowels 2
No of numbers 3
Method 2: Use indexOf to check for vowel or digit:
Instead of checking each vowel characters, we can use public int indexOf(int ch) method of the String class.
It takes a character as parameter and returns the index within the string of the first occurrence of the character. If character is not found, it returns -1. So, -1 means the character is not vowel if we call this method for string ’AEIOUaeiou’, isn’t it ?
Let’s modify the above program :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String inputStr;
int v = 0;
int n = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your string : ");
inputStr = scanner.nextLine();
for (int i = 0; i < inputStr.length(); i++) {
char c = inputStr.charAt(i);
if ("AEIOUaeiou".indexOf(c) != -1) {
v++;
} else if (Character.isDigit(c)) {
n++;
}
}
System.out.println("No of vowels " + v);
System.out.println("No of numbers " + n);
}
}
If you run this program, it will print similar output.
Similar tutorials :
- Java program to find closest number to a given number without a digit :
- Java program to find Harshad or Niven number from 1 to 100
- Java program to find out the top 3 numbers in an array
- Java Program to reverse a number
- Java program to find the kth smallest number in an unsorted array
- Java program to check if a number is Pronic or Heteromecic