Number Parsing in Mercury

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 parseFloat, we don't need to specify precision as in Go
        float f = Float.parseFloat("1.234");
        System.out.println(f);

        // For 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 used for basic base-10 int parsing
        int k = Integer.parseInt("135");
        System.out.println(k);

        // Parse functions throw exceptions on bad input
        try {
            int badNumber = Integer.parseInt("wat");
        } catch (NumberFormatException e) {
            System.out.println(e.getMessage());
        }
    }
}

Let’s break down the key points:

  1. Java provides wrapper classes like Float, Integer, and Long that offer methods for parsing strings into numbers.

  2. Unlike Go, Java doesn’t require specifying bit precision for floating-point parsing. Float.parseFloat() and Double.parseDouble() are used for this purpose.

  3. For integer parsing, Integer.parseInt() is commonly used. It doesn’t require specifying a base (radix) unless you’re parsing non-decimal numbers.

  4. Java can parse hexadecimal numbers using Integer.parseInt() with a radix of 16.

  5. For unsigned integers, Java provides Long.parseUnsignedLong().

  6. Java uses exceptions for error handling. When parsing fails, a NumberFormatException is thrown.

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 basic number parsing in Java. The language provides a rich set of parsing methods in its standard library, allowing for flexible and robust number parsing from strings.

Next, we’ll look at another common parsing task: URLs.