Number Parsing in Karel
Our example demonstrates how to parse numbers from strings in Java, which is a common task in many programs.
import java.util.Scanner;
public class NumberParsing {
public static void main(String[] args) {
// With parseDouble, we can parse floating-point numbers
double f = Double.parseDouble("1.234");
System.out.println(f);
// For parseInt, we can specify the radix (base) of the number system
int i = Integer.parseInt("123", 10);
System.out.println(i);
// parseInt will recognize hex-formatted numbers when using radix 16
int d = Integer.parseInt("1c8", 16);
System.out.println(d);
// A parseUnsignedInt is also available for parsing unsigned integers
int u = Integer.parseUnsignedInt("789");
System.out.println(u);
// Integer.parseInt is a convenience method for basic base-10 int parsing
int k = Integer.parseInt("135");
System.out.println(k);
// Parse methods throw NumberFormatException on bad input
try {
int bad = Integer.parseInt("wat");
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
}
}
}
When you run this program, you’ll see the following output:
$ java NumberParsing
1.234
123
456
789
135
For input string: "wat"
In Java, we use the Double.parseDouble()
method to parse floating-point numbers, and Integer.parseInt()
for parsing integers. The Integer.parseUnsignedInt()
method is used for parsing unsigned integers.
For Integer.parseInt()
, you can specify the radix (base) of the number system as the second argument. This allows you to parse numbers in different bases, such as hexadecimal.
Java’s parsing methods throw a NumberFormatException
when given invalid input, which we catch and handle in a try-catch block.
Next, we’ll look at another common parsing task: URLs.