1

Ok, I'm lost. I am required to figure out how to validate an integer, but for some stupid reason, I can't use the Try-Catch method. I know this is the easiest way and so all the solutions on the internet are using it.

I'm writing in Java.

The deal is this, I need someone to put in an numerical ID and String name. If either one of the two inputs are invalid I must tell them they made a mistake.

Can someone help me?

Mat
  • 202,337
  • 40
  • 393
  • 406
Phil
  • 10,948
  • 17
  • 69
  • 101
  • You don't specify what constitutes a valid String input. Technically everything input is a String so what's invalid? – cletus Mar 21 '10 at 02:48
  • Oh yeah, I guess I don't have to check for that. Thanks hahah, just integer validation! – Phil Mar 21 '10 at 02:56
  • Well how about a string that consists only of whitespace? That might be something you want to consider invalid. – Tyler Mar 21 '10 at 03:18

7 Answers7

5

If I understand you correctly, you are reading an integer or string from standard input as strings, and you want to validate that the integer is actually an integer. Perhaps the trouble you are having is that Integer.parseInt() which can be used to convert a String to an integer throws NumberFormatException. It sounds like your assignment has forbidden the use of exception-handling (did I understand this correctly), and so you are not permitted to use this builtin function and must implement it yourself.

Ok. So, since this is homework, I am not going to give you the complete answer, but here is the pseudocode:

let result = 0 // accumulator for our result
let radix = 10 // base 10 number
let isneg = false // not negative as far as we are aware

strip leading/trailing whitespace for the input string

if the input begins with '+':
    remove the '+'
otherwise, if the input begins with '-':
    remove the '-'
    set isneg to true

for each character in the input string:
    if the character is not a digit:
        indicate failure
    otherwise:
        multiply result by the radix
        add the character, converted to a digit, to the result

if isneg:
     negate the result

report the result

The key thing here is that each digit is radix times more significant than the digit directly to its right, and so if we always multiply by the radix as we scan the string left to right, then each digit is given its proper significance. Now, if I'm mistaken, and you actually can use try-catch but simply haven't figured out how:

int result = 0;
boolean done = false;
while (!done){
     String str = // read the input
     try{
         result = Integer.parseInt(str);
         done = true;
     }catch(NumberFormatException the_input_string_isnt_an_integer){
         // ask the user to try again
     }
}  
Michael Aaron Safyan
  • 93,612
  • 16
  • 138
  • 200
  • Or you could just use regular expressions, but that's probably overkill for this assignment. And of course you know what they say about someone who has a problem and thinks "I know -- I'll use regular expressions!" – Tyler Mar 21 '10 at 03:17
  • Wow. I'm actually taking a very basic java course, dang this really helped hahaha! – Phil Mar 21 '10 at 03:49
3

Not exactly sure if the String that is being validated should check whether the contents only contains numbers, or can be actually represented in the valid range of an int, one way to approach this problem is to iterate over the characters of a String and check that the characters are only composed of numbers.

Since this seems to be homework, here's a little bit of pseudocode:

define isANumber(String input):
  for (character in input):
    if (character is not a number):
      return false

  return true
coobird
  • 159,216
  • 35
  • 211
  • 226
2

You can use java.util.Scanner and hasNextInt() to verify if a String can be converted to an int without throwing an exception.

As an extra feature, it can skip whitespaces, and tolerates extra garbage (which you can check for).

String[] ss = {
   "1000000000000000000",
   "  -300  ",
   "3.14159",
   "a dozen",
   "99 bottles of beer",
};
for (String s : ss) {
   System.out.println(new Scanner(s).hasNextInt());
} // prints false, true, false, false, true

See also: How do I keep a scanner from throwing exceptions when the wrong type is entered?

Community
  • 1
  • 1
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
2

I'm using Java 1.6 and this works for me:

if (yourStringVariable.trim().matches("^\\d*$"))

then you've got a positive integer

Peter DeGregorio
  • 1,729
  • 1
  • 11
  • 5
0

Look at the hasNext methods in Scanner. Note that there are methods for each type (e.g. hasNextBigDecimal), not just hasNext.

EDIT: No, this will not throw on invalid input, only if the Scanner is closed prematurely.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • that is what I thought, but having input.hasNext() will still throw an exception.. won't it? – Phil Mar 21 '10 at 02:56
0
Pattern p = Pattern.compile("\\d{1,}");
Matcher m = p.matcher(inputStr); 
boolean isNumber = false;

if (m.find()) {
    isNumber = true;   
}
Laxmikanth Samudrala
  • 2,203
  • 5
  • 28
  • 45
  • This is the right idea, but you need to cater for an optional sign (easy) and the possibility of numbers that are too large (messy unless you limit the domain). – Stephen C Mar 21 '10 at 03:42
0
public static boolean IsNumeric(String s)
{
    if (s == null)
        return false;
    if (s.length() == 0)
        return false;
    for (int i = 0; i < s.length(); i++)
    {
        if (!Character.isDigit(s.charAt(i)))
            return false;
    }
    return true;
}     
rebeliagamer
  • 1,257
  • 17
  • 33
Arivu2020
  • 2,485
  • 7
  • 25
  • 24