The nextLine Trap
Completed
Read an age (integer) on the first line and a full name on the second line. Print NAME is AGE. Beware: nextInt() leaves the line break behind.
Input
Line 1: age. Line 2: full name.
Output
One line.
Example
Input
30 Grace Hopper
Output
Grace Hopper is 30
Editor
Java
Hints
After nextInt(), call nextLine() once to skip the end of that line.
Solution explanation
This is the most common Scanner bug: without the extra nextLine() you'd read an empty name.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
sc.nextLine(); // consume the rest of the first line
String name = sc.nextLine();
System.out.println(name + " is " + age);
}
}