Number Parsing in Java
Our program demonstrates parsing numbers from strings, which is a basic but common task in many programs. Here’s how to do it in Java:
import java.text.ParseException;
public class NumberParsing {
public static void main(String[] args) {
// With Double.parseDouble, we don't need to specify precision
double f = Double.parseDouble("1.234");
System.out.println(f);
// For Integer.parseInt, we don't need to specify the bit size
int i = Integer.parseInt("123");
System.out.println(i);
// Integer.parseInt can recognize hex-formatted numbers with a radix of 16
int d = Integer.parseInt("1c8", 16);
System.out.println(d);
// For parsing unsigned integers, we can use Integer.parseUnsignedInt
long u = Integer.parseUnsignedInt("789");
System.out.println(u);
// Integer.parseInt is the equivalent of Atoi for base-10 int parsing
int k = Integer.parseInt("135");
System.out.println(k);
// Parse methods throw NumberFormatException on bad input
try {
Integer.parseInt("wat");
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
}
}
}
Here’s a breakdown of the code:
We use
Double.parseDouble()
to parse floating-point numbers. Unlike in the original example, Java doesn’t require specifying the precision.Integer.parseInt()
is used for parsing integers. We don’t need to specify the base (it’s assumed to be 10) or the bit size.For parsing hexadecimal numbers, we use
Integer.parseInt()
with a radix of 16.Java doesn’t have a direct equivalent to
ParseUint
, but we can useInteger.parseUnsignedInt()
which returns a long to accommodate larger values.Integer.parseInt()
serves the same purpose asAtoi
for basic base-10 integer parsing.In Java, parse methods throw a
NumberFormatException
on bad input, which we catch and print.
When you run this program, you should see output similar to this:
1.234
123
456
789
135
For input string: "wat"
Next, we’ll look at another common parsing task: URLs.