how create a method that will only accept user input if its 1 character string long or else, print error

18 views Asked by At

task: take string input from user and determine if it is a vowel or a consonant. only accept input if its a string length of 1. If two letters then print error message.

note: i had this same code written, but all the data types were 'char', and the scanner was userInput.next().charAt(0); when everything noted as String was char data type, it could determine if the userInput was a vowel or a consonant. but the complications arised when I tried to add a new if statement that only accept the input as a one character string.

tried: I tried to use char.length(); but ofcoarse this doesnt work with char. Thats when i switched everything to string. now program wont work. the out put it now nothing.

current code:(nothing work except "Enter any ONE letter to see if its a vowel or consonant:"

import java.util.Scanner;

public class VowelOrConsonant { String l;

static String Vowel_Or_Consonant(String scanLetter){
    
    
    if(scanLetter == "a" || scanLetter == "e" || scanLetter == "i" ||  scanLetter == "o" || scanLetter == "u") {
        System.out.println("Letter entered is a vowel.");
    }else if(scanLetter == "b" || scanLetter == "c" || scanLetter == "d" || scanLetter == "f" || 
            scanLetter == "g" || scanLetter == "h" || scanLetter == "j" || scanLetter == "k" || scanLetter == "l"||
            scanLetter == "m" || scanLetter == "n" || scanLetter == "p" || scanLetter == "q" || scanLetter == "r"||
            scanLetter == "s" || scanLetter == "t" || scanLetter == "v" || scanLetter == "w" || scanLetter == "x" ||
            scanLetter == "y" || scanLetter == "z"){
        System.out.println("Letter entered is a consonant.");
    }//else {
        //System.out.println("ERROR: Only letter's are accepted. Try again.");
    //}
return scanLetter;
}

public String getLetter() {
    return l;
}

public void setLetter(String l) {
    this.l = l;
}

public static void main(String[] args) {
    VowelOrConsonant vc = new VowelOrConsonant(); //creates object 
    
    System.out.println("Enter any ONE letter to see if its a vowel or consonant:");
    Scanner userInput = new Scanner(System.in); //create variable for scanner
    String scanLetter = userInput.nextLine(); //get user input store in scanDay
    userInput.close();
    //take user input
    VowelOrConsonant.Vowel_Or_Consonant(scanLetter);
    //print sentence once user in-putted
    vc.getLetter(); //prints the day they've chosen
}

}

0

There are 0 answers