How to check if a vowel is present in a string

How to check if a vowel is present in a string.

Way 1: check if a vowel is present in a string:

import java.util.Scanner;

class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter a string: ");
		String input = scanner.nextLine();
		boolean vowelPresent = false;
		for (int i = 0; i < input.length(); i++) {
			char c = Character.toLowerCase(input.charAt(i));
			if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
				vowelPresent = true;
				break;
			}
		}
		if (vowelPresent) {
			System.out.println("The input string contains a vowel.");
		} else {
			System.out.println("The input string does not contain a vowel.");
		}
	}
}

In this program, we first ask the user to enter a string using the Scanner class. We then loop through each character in the string and check if it’s a vowel (either lowercase or uppercase). If we find a vowel, we set the vowelPresent variable to true and break out of the loop. Finally, we print a message depending on whether a vowel was found or not.

Way 2: Java code snippet to check if a vowel is present in a string:

public static boolean containsVowel(String str) {
String vowels = "aeiouAEIOU";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (vowels.indexOf(c) != -1) {
  return true;
    }
  }
return false;
}

In this code snippet, we define a method called containsVowel that takes a String as an argument and returns a boolean indicating whether the string contains at least one vowel.

The method first creates a String called vowels that contains all the vowel characters (both lowercase and uppercase). It then loops through each character in the input String, checking if it is a vowel by using the indexOf method of the String class to search for the character in the vowels string. If the character is found in vowels, the method returns true. If the loop completes without finding a vowel, the method returns false.

To use this method, you can simply call it and pass in a String as an argument. For example:

String myString = "Hello, world!";
if (containsVowel(myString)) {
    System.out.println("The string contains at least one vowel.");
} else {
    System.out.println("The string does not contain any vowels.");
}

This code will output “The string contains at least one vowel.” because the input string “Hello, world!” contains the vowel ‘o’.

How to reverse a string in Java?

How to check whether a string is a palindrome in Java?

Ram Chadar

Hello! I'm Ram Chadar, a passionate software developer and freelancer based in Pune. Welcome to my blog, where I share my experiences, insights, and knowledge in the world of software development, different technologies, freelancing, and more.

View all posts by Ram Chadar →

Leave a Reply

Your email address will not be published. Required fields are marked *