3

Forgive me I am new to programming, but thoroughly enjoy what I have learned so far. So my question is; I am trying to write a program that prompts the user to enter a letter, then returns whether the letter is a vowel or a consonant. Problem is I can not get it to accept a letter input. It will accept it if forced to as in "user_input = 'a'". But not as an option. I know am missing something simple.

public static void main(String[] args)
{
    Scanner in = new Scanner(System.in);
    int user_input;

    System.out.print("Enter a letter: ");
    user_input = in.nextInt();//<--line of error

    if (user_input == 'a')
    {
        System.out.println("Vowel");
    }
    else if (user_input =='e')
    {
        System.out.println("Vowel");
    }
    else if (user_input =='i')
    {
        System.out.println("Vowel");
    }
    else if (user_input =='o')
    {
        System.out.println("Vowel");
    }
    else if (user_input =='u')
    {
        System.out.println("Vowel");
    }
    else
    {
        System.out.println("Consonant");
    }
}

Thank you ahead of time for your time.

1 Answers1

3

Since you're reading a character, you should use the character type. additionally, you'd want to read the next character, not the next int. .next() will read the next string, then charAt(0) gets just the first character.

System.out.print("Enter a letter: ");
char user_input = in.next().charAt(0);

And if you want to be case insensitive:

char user_input = in.next().toLowerCase().charAt(0); 

You could also stand to reduce the repetition of the code by using a logical "or" instead of separate ifs

if (user_input == 'a'
 || user_input =='e'
 || user_input =='i'
 || user_input =='o'
 || user_input =='u')
{
    System.out.println("Vowel");
}
else
{
    System.out.println("Consonant");
}

However, you may prefer the switch syntax approach

switch (user_input) {
    case 'a':
    case 'e':
    case 'i':
    case 'o':
    case 'u':
        System.out.println("Vowel");
        break;
    default:
        System.out.println("Consonant");
        break;
}
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
  • Alternatively, OP could use a switch statement like [this](http://stackoverflow.com/a/16706729/3703709) – mstbaum Feb 12 '15 at 18:26
  • @mstbaum you'd prefer setting a variable rather than setting in the case as I have? I'm not quite sure I understand what you're suggesting differently – Ryan Haining Feb 12 '15 at 18:29
  • I think I skipped over your switch syntax part that you already provided and just didn't notice it. My bad. – mstbaum Feb 12 '15 at 18:36
  • This was very helpful, thank you. It worked and i added a error message in case something else was entered (like more then one letter or a number). – Papercuts_Ink Feb 13 '15 at 16:38