Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Java Dictionary

  1. Home
  2. Java Dictionary
  3. new Scanner() / scanner.nextLine() / nextInt()

new Scanner() / scanner.nextLine() / nextInt()

The Scanner class reads text from standard input (keyboard) or from files. It is commonly used to receive user input in console programs. Use nextLine() to read an entire line of text, and nextInt() to read an integer.

Syntax

// Creates a Scanner that reads from standard input (keyboard).
Scanner scanner = new Scanner(System.in);

// Reads an entire line as a String.
String line = scanner.nextLine();

// Reads the next token (delimited by whitespace) as a String.
String word = scanner.next();

// Reads an integer.
int num = scanner.nextInt();

// Reads a double.
double d = scanner.nextDouble();

// Checks whether there is another line to read.
scanner.hasNextLine();

Method List

MethodDescription
new Scanner(System.in)Creates a Scanner that reads from standard input (keyboard).
nextLine()Reads the rest of the current line as a String, excluding the newline character.
next()Reads the next token (a word delimited by spaces, tabs, or newlines) as a String.
nextInt()Reads the next token and returns it as an int.
nextDouble()Reads the next token and returns it as a double.
hasNextLine()Returns a boolean indicating whether another line of input exists.

Sample Code

import java.util.Scanner;

Scanner scanner = new Scanner(System.in);

// Reads one line for the name.
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");

// Reads an integer.
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Next year you will be " + (age + 1) + ".");

// After calling nextInt(), consume the leftover newline before calling nextLine().
scanner.nextLine(); // Discards the newline remaining in the buffer.

// Reads multiple lines.
System.out.println("Enter text (type 'end' to finish):");
while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    if (line.equals("end")) break;
    System.out.println("Input: " + line);
}

// Close the scanner when done.
scanner.close();

Notes

When you call nextLine() immediately after a method like nextInt(), it reads the leftover newline character in the buffer and returns an empty string. To avoid this, call scanner.nextLine() once right after reading a number to consume that newline.

If the input cannot be parsed as the expected type, an InputMismatchException is thrown. To handle user input safely, either use a try-catch block or read the input with nextLine() and convert it manually using Integer.parseInt().

For buffered input reading, see new BufferedReader() / readLine().

If you find any errors or copyright issues, please .