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:
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:
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.