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开发者_JAVA技巧 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?
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 } }
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
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?
I'm using Java 1.6 and this works for me:
if (yourStringVariable.trim().matches("^\\d*$"))
then you've got a positive integer
Pattern p = Pattern.compile("\\d{1,}");
Matcher m = p.matcher(inputStr);
boolean isNumber = false;
if (m.find()) {
isNumber = true;
}
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.
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;
}
精彩评论