Number Parsing in Miranda

import java.util.Scanner;

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

        // For parsing integers, we can use Integer.parseInt or Long.parseLong
        // depending on the size of the number
        long i = Long.parseLong("123");
        System.out.println(i);

        // Java can parse hexadecimal numbers using the same method
        long d = Long.parseLong("1c8", 16);
        System.out.println(d);

        // For parsing unsigned integers, we can use Long.parseUnsignedLong
        long u = Long.parseUnsignedLong("789");
        System.out.println(u);

        // Java doesn't have a direct equivalent to Atoi, but we can use Integer.parseInt
        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());
        }
    }
}

This program demonstrates number parsing in Java. Here’s how it works:

  1. We use Double.parseDouble() to parse floating-point numbers. Java’s double type is always 64-bit, so we don’t need to specify precision.

  2. For parsing integers, we use Long.parseLong(). This method can handle larger numbers than Integer.parseInt().

  3. Java can parse hexadecimal numbers using the same parseLong() method, by specifying the base (16 for hexadecimal) as the second argument.

  4. For parsing unsigned integers, we use Long.parseUnsignedLong().

  5. Java doesn’t have a direct equivalent to Go’s Atoi(), but Integer.parseInt() serves the same purpose for parsing base-10 integers.

  6. When parsing fails, Java throws a NumberFormatException. We demonstrate this by trying to parse an invalid input and catching the exception.

To run this program, save it as NumberParsing.java, compile it with javac NumberParsing.java, and then run it with java NumberParsing. The output will be similar to:

1.234
123
456
789
135
For input string: "wat"

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