Suggestion a) is nice. Concerning regular expressions, they might not be very suitable for the original poster (who was not even familiar with parseInt). Let's not make it too difficult for some who is new to Java.
@chaarmann
017 as octal number and 0x1a as hexadecimal number are valid when directly written in Java. For example, a ==b, a == c and b == c after these 3 lines of code:
-
int a = 017;
-
int b = 0xf;
-
int c = 15;
-
That is quite different from Integer.parseInt(String) which is documented to only work with base-10 numbers. For octal and hexadecimal numbers, there is Integer.parseInt(String, int), but though leading zero's are accepted, the 'x' of hexadecimal numbers is not, so a special check is necessary.
There is
-3 // decimal, accepted by parseInt
+4 // decimal, accepted by parseInt
245 // decimal, accepted by parseInt
-03 // octal, accepted by parseInt
+04 // octal, accepted by parseInt
0245 // octal, accepted by parseInt
-0x3 // hex, not accepted by parseInt ('x' not allowed)
+0x4 // hex, not accepted by parseInt ('x' not allowed)
0x245 // hex, not accepted by parseInt ('x' not allowed)
-
// Get the command line parameter as a String
-
String potentialNumber = args[i];
-
-
// Stores the parsed command line argument
-
int j;
-
-
try {
-
if (potentialNumber.length() == 0) {
-
throw new NumberFormatException("Empty string!");
-
}
-
-
// Start at index 0
-
int idx = 0;
-
-
// Skip (for now) leading + or - sign
-
char first = potentialNumber.charAt(0);
-
if (first == '+' || first == '-') {
-
idx++;
-
}
-
-
if (potentialNumber.charAt(idx) == '0') { // Octal or Hex?
-
idx++;
-
if (potentialNumber.charAt(idx) == 'x') { // Hex?
-
idx++;
-
// parseInt can't handle the 'x', so we only provide
-
// everything after the 'x' to parseInt
-
j = Integer.parseInt
-
(potentialNumber.substring(idx), 16);
-
// We possibly skipped a - sign, so check for that
-
if (first == '-') {
-
j *= -1;
-
}
-
} else { // Octal
-
// parseInt can handle the complete octal
-
// potentialNumber, including a possible + or - sign.
-
j = Integer.parseInt(potentialNumber, 8);
-
}
-
} else {
-
// Try to read the argument as a decimal integer
-
// parseInt can handle the complete decimal
-
// potentialNumber, including a possible + or - sign.
-
j = Integer.parseInt(potentialNumber);
-
}
-
} catch (NumberFormatException e) {
-
// Output an error message on the console
-
}
-