Paul Wagener said:
Hi folks,
Problem:
User is expected to input a String type.
How to check if the input is valid and not of Integer type?
Thanks a lot!
Paul
-------------------
If there is a '-', it must be first.
All other chars must be digits.
-------------------
public class TryInt {
public static void main(String[] args) {
String numStr = "-7898787";
int numInt = 0;
int start = 0;
boolean flag = false;
System.out.println("Input: \"" + numStr);
if (numStr.charAt(0) == '-') {
flag = true;
start = 1;
}
for (int i = start; i < numStr.length(); i++) {
char a = numStr.charAt(i);
if (Character.isDigit(a)) {
numInt = numInt * 10 + a - '0';
}
else {
System.err.println("Invalid integer character \'"
+ a + "\' at position " + i);
System.exit(1);
}
}
if (flag) numInt = -numInt;
System.out.println("Output: \"" + numInt);
}
}