← Java from Scratch
Lesson 51 of 88 · 5 XP
Warm-up: is it a number? warm-up
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
Integer.parseInt throws a NumberFormatException if the string isn't a number. You catch the error like this: the risky code goes in try, and what to do on error — in catch:
String s = in.nextLine();
try {
int n = Integer.parseInt(s);
System.out.println("ok " + n);
} catch (NumberFormatException e) {
System.out.println("not a number");
}
Task. Read a line. If it is an integer, print ok and the number separated by a space, otherwise not a number.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.