mardi 29 septembre 2020

Java Coding Help! Can't get if statement to confirm string

Write a program that prompts the user to provide a single character from the alphabet. Print Vowel or Consonant, depending on the user input. If the user input is not a letter (between a and z or A and Z), or is a string of length > 1, print an error message.

I have been trying to solve this problem, and basically have it all figured out but have ran into two issues. How do I get the scanner to recognize an error if the user inputs a number rather than a letter. Also how would one not have to repeat their input. Is there a way to have the first if statement evaluate if the user entered a string?

import java.util.*;

public class MessAround {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        
        System.out.println("Please Provide single character from the alphabet: ");
        String letter = scan.next();
        
        if (scan.hasNext())
        {
            letter = letter.toLowerCase();
            if (letter.equals("a") || letter.equals("e") || letter.equals("i") || letter.equals("o") || letter.equals("u"))
            {
                System.out.println("Vowel");
            }
            else if (letter.length() > 1)
            {
                System.out.println("Error");
            }
            else
            {
                System.out.println("Consonant");
            }
        }
        else
        {
            System.out.println("Error");
        }
    }

}

Aucun commentaire:

Enregistrer un commentaire