← Java from Scratch Lesson 47 of 88 · 10 XP

User input

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Scanner reads input by words (tokens) or by lines:

Scanner in = new Scanner(System.in);
int age = in.nextInt();          // a word → int
double h = in.nextDouble();
String word = in.next();         // one word
String line = in.nextLine();     // the rest of the current line, all of it
boolean more = in.hasNextInt();  // whether an integer comes next — without reading it

Beginners' trap no. 1: after nextInt() the line break stays unread, and the next nextLine() returns an empty string:

int n = in.nextInt();      // the input "25⏎Alex Kai⏎"
String name = in.nextLine();   // "" — we read the rest of the line with 25!
in.nextLine();                 // the fix: "eat" the rest of the line with a separate call

Input of "the wrong type" (abc instead of a number) throws an InputMismatchException.

Task. The input: a line with the full name, a line with the age, a line with the height (a fractional number), a line with the hobby (it may consist of several words). Print Name: …, In 5 years: …, Height: … m (2 decimal places), Hobby: ….

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.