Number Parsing in CLIPS

Our number parsing example demonstrates how to parse numbers from strings in Java. This is a common task in many programs.

import java.util.Scanner;

public class NumberParsing {
    public static void main(String[] args) {
        // With parseDouble, we don't need to specify precision
        double f = Double.parseDouble("1.234");
        System.out.println(f);

        // For parseInt, we don't need to specify the 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);

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

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

Let’s go through this code:

  1. We use Double.parseDouble() to parse a floating-point number. Unlike in Go, we don’t need to specify the precision.

  2. Integer.parseInt() is used to parse integers. We don’t need to specify the base (it defaults to 10) or bit size.

  3. For hexadecimal numbers, we can use Integer.parseInt() with a base of 16, or include the “0x” prefix and the method will automatically recognize it as hexadecimal.

  4. Java doesn’t have an unsigned int type, but we can use Long.parseUnsignedLong() to parse unsigned integers.

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

  6. In Java, parse methods throw a NumberFormatException on bad input, which we can catch and handle.

When you run this program, you should see output similar to this:

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

This example demonstrates the basic number parsing capabilities in Java. In the next example, we’ll look at another common parsing task: URLs.