Number Parsing in Fortress
Our number parsing program demonstrates how to parse numbers from strings in Java. Here’s the full source code:
Let’s break down the key points:
In Java, we use
Float.parseFloat()
andInteger.parseInt()
for parsing floating-point numbers and integers, respectively.Unlike Go, Java doesn’t require specifying the bit size when parsing. The methods automatically parse to the appropriate type (float, int, etc.).
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.Java provides
Long.parseUnsignedLong()
for parsing unsigned integers, which is similar toParseUint
in Go.In Java,
Integer.parseInt()
serves the same purpose asAtoi
in Go for basic base-10 integer parsing.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:
This example demonstrates how to parse various types of numbers from strings in Java, handling both successful parsing and error cases.