Skip to content
KALANBLON
Show contents

Chapter 2 of 6 · 15 min

Reading the keyboard and converting

By the end of this chapter, you'll be able to

  • Read a line from the keyboard with IO.readln
  • Convert a text into a number with Integer.parseInt and Double.parseDouble
  • Catch a NumberFormatException to handle invalid input
  • Clean up input with strip

Reading a line

IO.readln(message) displays the message, waits for the user to type a line and press Enter, then returns the typed text (without the line break):

void main() {
    String name = IO.readln("Your first name: ");
    IO.println("Nice to meet you, " + name + "!");
}
Sofia
Your first name: Nice to meet you, Sofia!

(In a real terminal, what you type appears after the question, and the answer comes on the next line.)

Converting into a number

IO.readln always returns a String. To calculate, you convert it:

  • Integer.parseInt(text) → an int;
  • Double.parseDouble(text) → a double (with a dot as the separator, whatever the system's language).
void main() {
    String input = IO.readln("Unit price: ");
    double price = Double.parseDouble(input.strip());
    int quantity = Integer.parseInt(IO.readln("Quantity: ").strip());
    IO.println();
    IO.println("Total: " + price * quantity);
}
2.5
 4 
Unit price: Quantity: 
Total: 10.0

strip() removes spaces at the start and end of the text: a space typed by mistake no longer makes the conversion fail. IO.println() with no argument simply moves to a new line.

Handling invalid input

If the text doesn't represent a number, parseInt throws an exception: an error signal that interrupts the program if nothing catches it, here a NumberFormatException. You can catch it with try … catch to react cleanly:

The catch block takes over: a clear message instead of a crash.

Step 5 of 5
Text description of the animation
  1. The user types 27: we get the text "27", not a number yet.
  2. parseInt converts it into the integer 27.
  3. The program carries on normally in the try block.
  4. With "twenty", the conversion fails: parseInt throws an exception, and the rest of the try block is skipped.
  5. The catch block takes over: a clear message instead of a crash.
void main() {
    String input = IO.readln("Your age: ");
    try {
        int age = Integer.parseInt(input.strip());
        IO.println("\nIn 10 years: " + (age + 10));
    } catch (NumberFormatException e) {
        IO.println("\nThat's not a whole number.");
    }
}
twenty
Your age: 
That's not a whole number.

We'll study exceptions in detail in the next course. For now, remember the pattern: the risky code in try, the reaction to the error in catch.

Your turn

Worked exercise

Worked exercise: temperature conversion

Write a program that reads a temperature in degrees Celsius, accepts a comma as well as a dot, and displays its value in degrees Fahrenheit (F = C × 9 / 5 + 32). If the input isn't a number, it displays Invalid temperature. For the input 36,6, it must display 36.6 °C = 97.88 °F.

Hint 1
input.strip().replace(',', '.') cleans up the input before Double.parseDouble.
Hint 2
String.format("%.2f", f) depends on the system's language. To always display a dot, round instead with Math.round(f * 100) / 100.0.
Show the solution and common mistakes
void main() {
    String input = IO.readln("Temperature in °C: ");
    try {
        double c = Double.parseDouble(input.strip().replace(',', '.'));
        double f = c * 9 / 5 + 32;
        IO.println();
        IO.println(c + " °C = " + Math.round(f * 100) / 100.0 + " °F");
    } catch (NumberFormatException e) {
        IO.println("\nInvalid temperature");
    }
}
36,6
Temperature in °C: 
36.6 °C = 97.88 °F

Common mistakes:

  • Writing c * (9 / 5) + 32: 9 / 5 is an integer division that gives 1. Without parentheses, c * 9 is a double, and the rest of the calculation keeps the decimals.
  • Dividing by 100 instead of 100.0 after Math.round: Math.round returns an integer, and the division would be an integer division.

Summary

  1. 1IO.readln(message) displays the message and returns the typed line, as a String.
  2. 2Integer.parseInt and Double.parseDouble convert a text into a number; parseDouble expects a dot.
  3. 3strip() removes the spaces around an input.
  4. 4Invalid input throws a NumberFormatException: catch it with try … catch.
  5. 5A clear message is better than a crash.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.