The Scanner class extracts individual tokens, separated by delimiters, from a source. The tokens can be returned as String objects or as other types, such as int or boolean.

The AP CS A Exam uses the Scanner class, with the File class, to extract tokens read from text files. See Reading files on the AP CS A Exam for discussion and examples.

For simplicity, the examples below use String objects as Scanner sources, which the AP CS A does not do.

Selected Scanner methods

Constructors

public Scanner(File source)

public Scanner(String source)

Each Scanner constructor accepts a source from which tokens are read. (There are other Scanner constructors, such as those that accept streams; however, they are neither featured on the AP CS A Exam nor useful for simple examples.)

The AP CS A Exam uses the constructor that accepts a File. Reading files on the AP CS A Exam explores this in detail.

The examples below use the constructor that accepts a String. Although this constructor is not used on the AP CS A Exam, it is helpful for examples and projects.

public String next()

public int nextInt()

public double nextDouble()

public boolean nextBoolean()

Each of these methods returns the next token from the source as the type shown. The methods that return types other than String throw an InputMismatchException if the next token’s type doesn’t match.

Each method throws a NoSuchElementException if called when the source does not have at least one remaining token. Each method throws an IllegalStateException if called after the Scanner has been closed.

hasNext method

public boolean hasNext()

hasNext returns true if the source has at least one token remaining to be read, false otherwise. hasNext does not check the type of the token, only whether a token is available to be read.

nextLine method

public String nextLine()

nextLine returns a String containing everything from the current Scanner position until the end of the line (or the end of the source).

Special care is required when combining calls to the methods above (next, nextInt, nextBoolean) with calls to nextLine in the same code. See Keyboard input with mixed types for discussion and an example.

The AP CS A Exam will not feature code that combines calls to nextLine with calls to next (or related methods). Students often accidentally write code that does this without considering the implications.

A line read with nextLine may be parsed with the String method split. See Reading files on the AP CS A Exam Example 2 for a demonstration. See split on the AP CS A Exam for details on the split method.

Example 1

String str = "Brandon Brenda    Evan\nMurray\nCactus";
Scanner fromStr = new Scanner(str);

while(fromStr.hasNext())
{
    String token = fromStr.next();
    System.out.println(token);
}

fromStr.close();

The code segment prints:

Brandon
Brenda
Evan
Murray
Cactus

Unless configured otherwise, a Scanner uses whitespace as a delimiter. Whitespace includes one or more spaces (" ") and a newline ("\n"). This means the Scanner considers each value separated by whitespace as a separate token.

Delimiters themselves are not included in the strings returned by calls to next. Only the strings between the delimiters are returned.

Example 2 (mixed types)

This example is adapted from the 2021 ClubMembers Free Response (#3).

String str = "2019 false SMITH, JANE 2018 true FOX, STEVE";
Scanner fromStr = new Scanner(str);

while(fromStr.hasNext())
{
    int year = fromStr.nextInt();
    boolean good = fromStr.nextBoolean();
    String last = fromStr.next();
    String first = fromStr.next();
    System.out.println(year + " " + good + " " + last + " " + first);
}

fromStr.close();

The code segment prints:

2019 false SMITH, JANE
2018 true FOX, STEVE

The example assumes that the values in str consist of records for individual students, each in a precise format. Specifically, it assumes that each record consists of four tokens: an int representing a year, a boolean representing good standing, a String representing last name (followed by a comma), and a String representing first name. Both records and tokens within records are seperated by a space.

The example uses hasNext to determine if another record is available to be read. If another record is available, the body of the loop reads each of the four tokens, each as its type.

The example prints each record on its own line, with spaces between each token. Note that the spaces must be included in the println statement as they are not included in the tokens themselves. Also note that last includes the comma at the end of the last name, as a comma is not (by default) treated as a delimiter.

Example with error

String str = "happy sad mad";
Scanner fromStr = new Scanner(str);

while(fromStr.hasNext())
{
    if(fromStr.next().equals("happy"))
        System.out.println("Happy is good.");
    else if(fromStr.next().equals("sad"))
        System.out.println("Sorry your are sad.");
    else if(fromStr.next().equals("mad"))
        System.out.println("Don't be mad.");
}

fromStr.close();

The code segment prints:

Happy is good.

then crashes with a NoSuchElementException.

The code segment incorrectly calls next more than once per loop execution, expecting that the same value is returned each time. Each call to next advances the Scanner past returned token.

The first time the loop executes, the call to next (in the first condition) returns "happy". The code prints "Happy is good." and proceeds to the next loop execution.

The second time the loop executes, the call to next in the first condition returns "sad". The condition is false. The call to next in the second condition returns "mad". The condition is false. The call to next in the third condition throws a NoSuchElementException because there is token remaining to be read.

Corrected code

String str = "happy sad mad";
Scanner fromStr = new Scanner(str);

while(fromStr.hasNext())
{
    String feeling = fromStr.next();
    if(feeling.equals("happy"))
        System.out.println("Happy is good.");
    else if(feeling.equals("sad"))
        System.out.println("Sorry your are sad.");
    else if(feeling.equals("mad"))
        System.out.println("Don't be mad.");
}

fromStr.close();

The corrected code segment prints:

Happy is good.
Sorry your are sad.
Don't be mad.

Each loop execution calls next once and saves the return value in feeling. The value can then be used repeatedly without advancing the Scanner.

Documentation

The 2025 AP CS A Course Description documents the Scanner methods used on the AP CS A Exam (PDF page 113, page number 106 on bottom).

The Scanner class Java API documentation documents every method, including many that are not featured on the AP CS A Exam.

Additional resources

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on Using the Scanner class