Java Program: String input validation for vowels
7. Throw Exception if String Has No Vowels
Write a Java program to create a method that takes a string as input and throws an exception if the string does not contain vowels.
Sample Solution:
Java Code:
Sample Output:
String contains vowels. Original string: Java handling and managing exceptions
Original string: Typy gyps fly. Error: String does not contain any vowels
Explanation:
In the above exercise,
- The main method is defined in the Vowel_Check class and serves as the program entry point.
- In the main method, a string of text is initialized with a value. This string represents the input to be checked for vowels.
- The checkVowels method is called, passing the text string as an argument. This method checks if the string contains vowels.
- Inside the checkVowels method, a boolean variable containsVowels is initialized as false. This variable tracks whether vowels are found in the string.
- A for loop iterates through each character of the text string.
- After the loop, if containsVowels is still false, it means no vowels were found in the string. In this case, a NoVowelsException is thrown with the message "String does not contain any vowels."
- The NoVowelsException class is a custom exception class that extends the base Exception class. It provides a constructor that takes a message parameter and passes it to the superclass constructor using the super keyword.
- If a NoVowelsException occurs in the main method, it is caught, and an appropriate error message is printed.
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to create a method that accepts a string and throws a NoVowelException if it contains no vowels.
- Write a Java program to validate a string input case-insensitively and throw an exception if it does not contain at least one vowel.
- Write a Java program to check if a string consists solely of consonants and throw an exception if so.
- Write a Java program to create a method that scans a string for vowels and, if none are found, throws a custom exception while logging the input.
Go to:
PREV : Throw Exception for Duplicate Integers.
NEXT : Java Lambda Exercises Home.
Java Code Editor:
Improve this sample solution and post your code through Disqus
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.