SwadhyAI Notes

All Java notes

Java Scanner Methods Reference

›Short versionOpen if you only have a minute.
  • Scanner splits input into tokens. The default delimiter is whitespace.
  • next reads one token. nextLine reads the rest of the current line, including the leftover newline.
  • nextInt and nextDouble parse the next token. A token of the wrong shape throws InputMismatchException.
  • hasNextInt and hasNextDouble look ahead and do not consume the token.
  • After nextInt, the line break is still waiting. The next nextLine often returns an empty string.
  • close on a Scanner wrapped around System.in closes standard input for the rest of the program.

Scanner reads tokens from input sources such as System.in, strings, and files. It is convenient for beginner parsing, but delimiter and newline behavior needs care.

Methods

APIParametersReturnsBehaviorWatch for
next()None.Next token as String.Skips delimiters and reads until the next delimiter.Default delimiter is whitespace, so spaces split input.
nextLine()None.Remaining text on the current line.Consumes the line separator and returns text before it.After nextInt(), an immediate nextLine() may read the leftover newline.
nextInt() / nextDouble()None.Parsed primitive value.Parses the next token as the requested type.Throws InputMismatchException if the token has the wrong format.
hasNextInt() / hasNextDouble()None.boolean.Checks whether the next token can be parsed as that type.Does not consume the token.
useDelimiter(String pattern)Regex delimiter.This Scanner.Changes how tokens are separated.Delimiter is regex, so special characters need escaping.
close()None.void.Closes scanner and underlying source if closeable.Closing Scanner(System.in) closes standard input.

Which call fits

OptionBest forTradeoff
ScannerSmall console programs and simple token parsing.Slower and more stateful than BufferedReader.
BufferedReaderFast line input and manual parsing.You parse numbers yourself.
ConsoleInteractive terminal input, especially password reads.May be null in IDEs and redirected environments.

Examples

Avoid the nextLine trap

java
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
sc.nextLine(); // consume leftover newline

String name = sc.nextLine();
System.out.println(name + " is " + age);

Validate before parsing

java
if (sc.hasNextInt()) {
    int count = sc.nextInt();
    System.out.println(count);
} else {
    System.out.println("Please enter a whole number.");
}

nextInt() just read 30 from the line 30 followed by Enter. What does the next nextLine() return?

An empty string. The digits are gone, and the newline is still in the scanner. nextLine() consumes that newline and returns the text before it, which is nothing. A second nextLine() waits for the next line of input.