Number Parsing in Logo
Our first example demonstrates parsing numbers from strings, which is a common task in many programs. Here’s how to do it in Java:
import java.util.Scanner;
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 base or 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 Long.parseUnsignedLong
long u = Long.parseUnsignedLong("789");
System.out.println(u);
// Integer.parseInt is the equivalent of Atoi for basic base-10 int parsing
int k = Integer.parseInt("135");
System.out.println(k);
// Parse methods throw NumberFormatException on bad input
try {
int badNumber = Integer.parseInt("wat");
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
}
}
}
Let’s break down the key points:
Java provides wrapper classes like
Double
,Integer
, andLong
that offer parsing methods.Double.parseDouble()
is used for parsing floating-point numbers. Unlike in the original example, we don’t need to specify precision.Integer.parseInt()
is used for parsing integers. By default, it assumes base 10. For other bases, you can specify the radix as a second argument.For parsing hexadecimal numbers, we use
Integer.parseInt()
with a radix of 16.Java doesn’t have a built-in unsigned integer type, but
Long.parseUnsignedLong()
can be used to parse unsigned integers.Integer.parseInt()
serves the same purpose asAtoi
in the original example for basic base-10 integer parsing.These parsing methods throw a
NumberFormatException
when given invalid input, which we catch and handle in a try-catch block.
When you run this program, you should see output similar to this:
1.234
123
456
789
135
For input string: "wat"
This example demonstrates how to parse various types of numbers from strings in Java. In the next example, we’ll look at another common parsing task: URLs.