Number Parsing in Fortress

Our number parsing program demonstrates how to parse numbers from strings in Java. Here’s the full source code:

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);

        // parseInt will recognize hex-formatted numbers with a "0x" prefix
        int d = Integer.parseInt("0x1c8", 16);
        System.out.println(d);

        // parseUnsignedInt is available for parsing unsigned integers
        long u = Long.parseUnsignedLong("789");
        System.out.println(u);

        // Integer.parseInt is the equivalent of Atoi in Go
        int k = Integer.parseInt("135");
        System.out.println(k);

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

Let’s break down the key points:

  1. In Java, we use Float.parseFloat() and Integer.parseInt() for parsing floating-point numbers and integers, respectively.

  2. Unlike Go, Java doesn’t require specifying the bit size when parsing. The methods automatically parse to the appropriate type (float, int, etc.).

  3. For parsing hexadecimal numbers, we can use Integer.parseInt() with a radix of 16, or include the “0x” prefix and let Java infer the base.

  4. Java provides Long.parseUnsignedLong() for parsing unsigned integers, which is similar to ParseUint in Go.

  5. In Java, Integer.parseInt() serves the same purpose as Atoi in Go for basic base-10 integer parsing.

  6. Instead of returning errors, Java’s parsing methods throw NumberFormatException when given invalid input. We use a try-catch block to handle this.

To run the program, save it as NumberParsing.java, compile and execute it:

$ javac NumberParsing.java
$ java NumberParsing
1.234
123
456
789
135
For input string: "wat"

This example demonstrates how to parse various types of numbers from strings in Java, handling both successful parsing and error cases.