Octal Octal - 2 months ago 6
Java Question

If statement help (noob)

I was trying to grab the first character from user entry, and determine it to be a vowel or not. I am very new, and have been struggling with this for a while. I am trying to add all vowels to the variable 'vowel', and not only will that obviously not work, but I feel like I am going the long way. Any help at all is vastly appreciated as I am very new to this.

entry = scanner.nextLine();
letters = entry.substring(0,1);
holder = entry.substring(1);
vowels = "A";


if (entry.substring(0,1).equals(vowels)) {
pigLatinVowel = entry + "way";
System.out.println(pigLatinVowel);
}

Answer

First, since you only want one character, don't use string methods, i.e. use entry.charAt(0) == 'A' instead of entry.substring(0,1).equals("A").

With that, you can then turn it around:

"AEIOU".indexOf(entry.charAt(0))

If the character at position 0 in the entry variable can be found, indexOf() returns the index position (zero-based), otherwise it returns -1.

So, to see if it is a vowel, do this:

if ("AEIOU".indexOf(entry.charAt(0)) != -1) {
    pigLatinVowel = entry + "way";
    System.out.println(pigLatinVowel);
}
Comments