SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser
Chapter:
Java Primer
Exercise:
Exercises
Question:8 | ISBN:9781118771334 | Edition: 6

Question

Write a short Java method that counts the number of vowels in a given character string.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

package java_problems_datastructures;

import java.util.Scanner;

public class CountVowels {

	static String string;

	private static void enterString() {

		// read input from the scanner;

		Scanner input = new Scanner(System.in);
		System.out.println("Enter a sring value: ");
		string = input.nextLine();
		
		// convert to lowercase
		string.toLowerCase();
		// remove all spaces using the replaceAll method 
		string = string.replaceAll("\\s", "");
		input.close();

	}

	private static int countVowels(String s) {

		// set count to zero initially
		int count = 0;

		// convert string to array of characters to find vowels
		char[] charArray = string.toCharArray();

		// check if they match with vowels using for loop

		for (int i = 0; i < string.length(); i++) {

			if (charArray[i] == 'a' || charArray[i] == 'e' || charArray[i] == 'i' || charArray[i] == 'o'
					|| charArray[i] == 'u') {

				count++;

			}

		}

		return count;

	}

	public static void main(String[] args) {

		enterString();

		// print count value

		System.out.println("Total vowels in the string is " + countVowels(string));

	}

}

 

0 0

Discussions

Post the discussion to improve the above solution.