Can't see me
Can't see me

Reputation: 501

Strings, how to recognize letters

I am a beginner in java and my questions might seem a little hideous, help would be appreciated though!

Anyways my question well the question in the book is :

"Write a program that prompts the user to provide a single character from the alpha­ bet. 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.

How can you detect if the input is not a letter or not, help would be appreciated! Thanks!

Upvotes: 0

Views: 2791

Answers (4)

No Idea For Name
No Idea For Name

Reputation: 11577

input in most common languages is in ACII. to see what an ascii, look at this table enter image description here
(source: cdrummond.qc.ca)

when you receive a letter from the user, you get a char. this char contains a number which is a letter, in respect to the ASCII table, meaning that if you have 75 in your char, you have a 'K'

now, to know if you got a letter, all you need to do is:

char c;// Your char

Scanner scan = new Scanner (System.in);
c = scan.nextChar();

if((c>= 'a' && c<= 'z') || (c>= 'A' && c<= 'Z'))
{
  // you got a letter
}
else
{
  //That's not a letter
}

you can do that, because the letter are one after the other, but you can't do

if(c>= 'A' && c<= 'z')

because there are several signs between them

Upvotes: 2

Jake Lin
Jake Lin

Reputation: 11494

The simple one would be like this

public static final int VOWEL = 0;
public static final int CONSONANT = 1;
public static final int OTHER = 2;

public int getCharType(char c) {
  switch(c) {
    case 'a':
    case 'A':
    case 'e':
      ...
      return VOWEL;

    case 'b':
    case 'B':
    case 'c':
      ...
      return CONSONANT;

    default:
      return OTHER;
  }
}

Upvotes: 0

Edward Falk
Edward Falk

Reputation: 10063

I'm going to skip over the part where you read a single character, but what you're looking for probably looks like this:

if (!chr.isLetter()) {
    // error
} else if ("aeiou".contains(chr.toLowerCase()) {
    // vowel
} else {
    // consonant
}

Handling non-ascii letters, locales, etc. is also left as an exercise to the reader.

Upvotes: 0

Dimitar Dimitrov
Dimitar Dimitrov

Reputation: 15148

Maybe you can look into regular expressions (not my favorite approach if I'm honest), but it's short and it does the job (also it might give you a different prospective):

String letterPattern = "^(?i)[a-z]$";
String vowelPattern = "^(?i)[aeoui]$";
String test = "A";

if(test.matches(letterPattern)) {
    if(test.matches(vowelPattern)) {
        System.out.println("This is a vowel!");
    }
    else {
        System.out.println("It's not ...");
    }           
}
// you get the idea ...

Upvotes: 1

Related Questions