views:

1001

answers:

4

I'm taking user input from System.in using a java.util.Scanner. I need to validate the input for things like:

  • It must be a non-negative number
  • It must be an alphabetical letter
  • ... etc

What's the best way to do this?

A: 

You can check the ascii value for the characters and write your conditions.

ckv
can u pls code it.
bhavna raghuvanshi
+11  A: 
polygenelubricants
this code is working for negative numbers but not for alphabet
bhavna raghuvanshi
That's probably the best way yo go about it, depending on the input method, of course.
Nubsis
@bhavna: learn from the code and do the rest yourself.
polygenelubricants
@bhavna, please stop expecting others to do all **your** work. Also, thanking someone from time to time wouldn't hurt either.
Bart Kiers
A: 

If you are parsing string data from the console or similar, the best way is to use regular expressions. Read more on that here: http://java.sun.com/developer/technicalArticles/releases/1.4regex/

Otherwise, to parse an int from a string, try Integer.parseInt(string). If the string is not a number, you will get an exception. Otherise you can then perform your checks on that value to make sure it is not negative.

String input;
int number;
try
{
    number = Integer.parseInt(input);
    if(number > 0)
    {
        System.out.println("You positive number is " + number);
    }
} catch (NumberFormatException ex)
{
     System.out.println("That is not a positive number!");
}

To get a character-only string, you would probably be better of looping over each character checking for digits, using for instance Character.isLetter(char).

String input
for(int i = 0; i<input.length(); i++)
{
   if(!Character.isLetter(input.charAt(i)))
   {
      System.out.println("This string does not contain only letters!");
      break;
   }
}

Good luck!

Nubsis
A: 

One idea:

try {
    int i = Integer.parseInt(myString);
    if (i < 0) {
        // Error, negative input
    }
} catch (NumberFormatException e) {
    // Error, not a number.
}

There is also, in commons-lang library the CharUtils class that provides the methods isAsciiNumeric() to check that a character is a number, and isAsciiAlpha() to check that the character is a letter...

romaintaz