Answer to Question #286045 in Java | JSP | JSF for Hamza

Question #286045

In this task, you are being asked to write void methods in Java.

Write a method called wordsInfo() that accepts one String argument, and prints how many

characters are there in that argument, as well as the number of vowels.

You may use the following header for this method:

static void wordsInfo(String word)

For this exercise, assume that a e i o u y are vowels. For example, if the method is called with an

argument "Harry", the method prints:

wordsInfo(“Harry”);

//method prints

5 characters.

2 vowels.

1. Create a program called CharactersLab1.java

2. Create appropriate variables and assign values using a Scanner object.

3. Correctly display appropriate messages.


1
Expert's answer
2022-01-09T13:06:16-0500
import java.util.Scanner;

public class Main
{
    static void wordsInfo(String word) {
        int chars = 0, vowels = 0;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'y')
                vowels++;
            chars++;
        }
        // you can get number of characters by calling word.length() method, so no need to use 'chars' variable
        System.out.println(chars + " characters.");
        System.out.println(vowels + " vowels.");
    }

    public static void main (String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a word:");
        String word = in.next();

        wordsInfo(word);
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog