Answer to Question #235998 in Java | JSP | JSF for jerry

Question #235998

Create an array of characters which will be initialized during run time with vowels.

If user enters any consonant, your code should generate a user-defined checked

exception, InvalidVowelException. The description or message of

InvalidVowelException is "character is consonant". Handle the exception by using

try, catch, finally, throw and throws.


1
Expert's answer
2021-09-12T11:48:56-0400
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try {
            char[] vowelArray = createVowelArray();
            System.out.println("Array created");
        } catch (InvalidVowelException exception) {
            System.out.println(exception.getMessage());
        } finally {
            System.out.println("End of program");
        }
    }

    public static char[] createVowelArray() throws InvalidVowelException {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter size of array: ");
        int size = scanner.nextInt();
        char[] vowelArray = new char[size];
        String vowels = "aeiouAEIOU";
        for (int i = 0; i < size; i++) {
            System.out.print("Enter vowel: ");
            vowelArray[i] = scanner.next().charAt(0);
            if (vowels.indexOf(vowelArray[i]) == -1)
                throw new InvalidVowelException("character is consonant");
        }
        return vowelArray;
    }

    static class InvalidVowelException extends Exception {
        public InvalidVowelException(String message) {
            super(message);
        }
    }
}

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
APPROVED BY CLIENTS