Number Parsing in Minitab

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

        // There's no direct equivalent to Atoi in Java, but parseInt serves the same purpose
        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:

  1. Java provides wrapper classes like Double, Integer, and Long for parsing numbers from strings.

  2. Double.parseDouble() is used to parse floating-point numbers. Unlike in some other languages, we don’t need to specify precision.

  3. Integer.parseInt() is used for parsing integers. By default, it assumes base 10, but you can specify a different base as a second argument.

  4. For hexadecimal numbers, you can either use Integer.parseInt() with base 16, or include the “0x” prefix in the string and use base 16.

  5. Java doesn’t have an unsigned integer type, but Long.parseUnsignedLong() can be used to parse unsigned integers up to 64 bits.

  6. There’s no direct equivalent to Atoi in Java, but Integer.parseInt() serves the same purpose for parsing base-10 integers.

  7. Instead of returning an error, Java’s parse methods throw a NumberFormatException when given invalid input. We use a try-catch block to handle this.

To run this program:

$ 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. Next, we’ll look at another common parsing task: URLs.