Java
nextInt and nextLine
Learn type conversion with nextInt() and nextLine().
Read numbers with nextInt
nextInt() reads an integer from the console. nextDouble() is used for decimal numbers. These methods read the number but leave the trailing \n in the buffer.
Scanner input = new Scanner(System.in);
System.out.print("Age: ");
int age = input.nextInt();
System.out.println("Your age " + age);
If you call nextLine() right after reading a number, you get an empty string; the leftover \n is consumed at once. This trap is covered in the next card. For now, grasp the basics of reading numbers.
The nextInt and nextLine trap
nextInt() reads the number but leaves the trailing \n. If you then call nextLine(), the leftover \n is consumed at once and you get an empty string. The fix: after reading a number, call an empty nextLine() to clear the rest of the line.
int age = input.nextInt();
input.nextLine(); // clear leftover \n
String name = input.nextLine();
This pattern is a common mistake. Whenever you read text after a number, always insert a nextLine() in between. That way the next nextLine() reads the real user input.
Exercise Age and name together
Read the user's age (nextInt) first, then their name (nextLine). Remember to clear the leftover line after the number. Print Hello <name>, you are <age>. The user will type 30 then Mehmet.
Show example solution
System.out.print("Yaş: ");
int age = input.nextInt();
input.nextLine();
System.out.print("Ad: ");
String name = input.nextLine();
System.out.println("Merhaba, " + name + ", " + age + " yaşındasın");
Test yourself
-
Read the age
System.out.print("Age: ");
int age = input.____();
System.out.println(age);
Show answer
System.out.print("Age: ");
int age = input.nextInt();
System.out.println(age);
-
What is the value of name after this code?
int n = input.nextInt();
String name = input.nextLine();
(The user types 25 and presses Enter, then types Ayşe and presses Enter.)
- Ayşe
- 25
- 25Ayşe
- Empty string ("")
Show answer
Empty string ("") — nextInt reads 25 but leaves \n; nextLine consumes the leftover \n at once and returns an empty string.
-
Match each read method to its type
- nextInt()
- int
- nextDouble()
- double
- nextLine()
- String
- nextBoolean()
- boolean
Next lesson: System.out.printf