views:

325

answers:

6

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?

A: 

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
that is what I thought, but having input.hasNext() will still throw an exception.. won't it?
Phil
+2  A: 

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
+3  A: 

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
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!"
MatrixFrog
Wow. I'm actually taking a very basic java course, dang this really helped hahaha!
Phil
A: 
Pattern p = Pattern.compile("\\d{1,}");
Matcher m = p.matcher(inputStr); 
boolean isNumber = false;

if (m.find()) {
    isNumber = true;   
}
Laxmikanth Samudrala
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
A: 
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; }

Arivu2020
+1  A: 

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?

polygenelubricants