Number Parsing

Figure 525. Parsing Integer user input Slide presentation
String userInput = null;
try (final Scanner scanner =
  new Scanner(System.in)){
  System.out.print("Enter an integer:");
  userInput = scanner.nextLine();

  final int value = Integer.parseInt(userInput);

  System.out.println("You entered " + value);
} catch (final NumberFormatException e) {
  System.out.println("Sorry, but '" + userInput + 
  "' is not an integer.");
}
Enter an integer:-34
You entered -34
Enter an integer:five
Sorry, but 'five' is
not an integer.

exercise No. 178

Why using String userInput = null?

Q:

The former listing initializes the userInput variable using a default value null. Why is that?

  1. The variable userInput is being assigned inside the try {...} block before being used in any assignment.

  2. The Scanner.nextLine() method does not throw a NumberFormatException. Thus the only way to enter the catch {...} clause is by executing of Integer.parseInt(userInput) yielding a NumberFormatException . But this execution happens after assigning userInput = scanner.nextLine().

So the dummy assignment String userInput = null seems to be redundant. Is that true?

A:

Actually the Java compiler is not clever enough analyzing the try {...} block. The catch clause can only be reached by inadequate user input causing the parseInt(...) method. In particular the nextLine(...) being unable to throw a NumberFormatException cannot be the culprit for entering the catch clause. Thus if a NumberFormatException is being thrown our userInput variable will already carry a user entered input string. The compiler however cannot analyze this type of dependency.

Thus the possibility of an uninitialized userInput variable using just String userInput; would cause a compile time error Variable 'userInput' might not have been initialized.

So userInput = null is sufficient for keeping the compiler happy and inside the catch clause the variable will definitively carry a String reference.

Figure 526. Parsing binary representation Slide presentation
final int value =
   Integer.parseInt("1101", 2);
System.out.println("Value: " + value);
Value: 13
final int value =
  Integer.parseInt("201", 2);
System.out.println("Value: " + value)
Exception in thread "main"
 java.lang.NumberFormatException:
 For input string: "201"
...
  at de.hdm_stuttgart.sd1...


exercise No. 179

Parsing short values

Q:

Which outcome do you expect? Try to answer without prior execution.

System.out.println(Short.parseShort("32767"));
System.out.println(Short.parseShort("32768"));

Explain the result.

A:

MAX_VALUE for primitive type short is 2 16 - 1 - 1 which equals 32767. Thus 32786 is no longer assignment compatible. So the first line will execute well but the second one yields a NumberFormatException at runtime :

Value:32767
Exception in thread "main" java.lang.NumberFormatException:
     Value out of range. Value:"32768" Radix:10 at
     java.lang.Short.parseShort(Short.java:120)
  at java.lang.Short.parseShort(Short.java:144)
  at de.hdm_stuttgart.sd1.ParseShortTooBig.main(ParseShortTooBig.java:8)

exercise No. 180

Parsing short values in hexadecimal representation

Q:

An image processing application yields the following type of data:

String[] values = {"C9", "AF3", "B"}; // Hexadecimal string values

We are looking for a class method parsing these hex values and converting them to short:

/**
 * Convert a numerical value given as hexadecimal string  to
 * its counterpart of type short. Example:
 *
 * "2B" equals 2 * 16 + 11 == 43
 *
 * @param input String containing hexadecimal value.
 * @return the parsed short value.
 */
public static short getHexadecimal(final String input) {
  ...
  return ...;
}

The provided sample data may then be processed like:

final String[] values = {"C9", "AF3", "B"};

for (final String value: values) {
  System.out.println(value + ": " + getHexadecimal(value));
}

Result:

C9: 201
AF3: 2803
B: 11

Tip

Have a look to the binary parse example and think about representations.

A:

Hexadecimal representation uses a radix value of 16 to be passed to short parseShort​(String s, int radix):

/**
 * Convert a numerical value given as hexadecimal string  to
 * its counterpart of type short. Example:
 *
 * "2B" equals 2 * 16 + 11 == 43
 *
 * @param input String containing hexadecimal value.
 * @return the parsed short value.
 */
public static short getHexadecimal(final String input) {
  return Short.parseShort(input, 16);
}

A:

MAX_VALUE for primitive type short is 2 16 - 1 - 1 which equals 32767. Thus 32786 is no longer assignment compatible. So the first line will execute well but the second one yields a NumberFormatException at runtime :

Value:32767
Exception in thread "main" java.lang.NumberFormatException:
     Value out of range. Value:"32768" Radix:10 at
     java.lang.Short.parseShort(Short.java:120)
  at java.lang.Short.parseShort(Short.java:144)
  at de.hdm_stuttgart.sd1.ParseShortTooBig.main(ParseShortTooBig.java:8)