import java.util.Scanner; public class VowelChecker { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a string: "); String input = scanner.nextLine(); if (containsVowel(input)) { System.out.println("The string contains at least one vowel."); } else { System.out.println("The string does not contain any vowel."); } scanner.close(); } public static boolean containsVowel(String str) { str = str.toLowerCase(); // Convert the string to lowercase for case-insensitive comparison for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { return true; // Return true if a vowel is found } } return false; // No vowel was found in the string } } (code-box)
Explanation:
1. The program begins by importing the necessary class `Scanner` from the `java.util` package, which is used to read user input.
2. In the `main` method, the program prompts the user to enter a string.
3. The `containsVowel` method is defined to check whether a given string contains a vowel. It takes a string as a parameter.
4. Inside the `containsVowel` method, the input string is converted to lowercase using the `toLowerCase()` method. This is done to make the vowel comparison case-insensitive, as vowels can appear in both uppercase and lowercase forms.
5. The method then iterates through each character in the modified string using a `for` loop. For each character, it checks if it is one of the vowels 'a', 'e', 'i', 'o', or 'u'.
6. If a vowel is found, the method immediately returns `true`.
7. If the loop completes without finding any vowel, the method returns `false`.
8. Back in the `main` method, the `containsVowel` function is called with the user's input string. Depending on the return value, the program prints whether the string contains at least one vowel or not.
9. Finally, the `Scanner` is closed to release the system resources.
You can run this program, enter a string, and it will let you know if the string contains any vowels.
🚀 Elevate Your Career with Studyecart! 📚📊
🔥 Get instant job notifications and ace interviews with Studyecart. 📌
#StudyecartApp #CareerBoost