Concepts / TextIO and User Input

TextIO and User Input

Scanner is a standard Java alternative to TextIO for user input.

  • Programming

Why Input Needs a Scanner

A program that asks the user for a number needs a way to receive what the user types. In Java, one standard tool for this job is the Scanner class. The TextIO library is another option for user input, and Scanner is presented in the source as a standard Java alternative to it. This article follows one value from the keyboard into a program, so you can see exactly what each line of code is responsible for.

A common first reaction is that Scanner looks difficult. It does need a little more visible setup than a single TextIO call: an import line, a variable, and a constructor expression. But the basic pattern is short. You make the Scanner class available, you create a Scanner variable, and you call an input method on that variable. Each of those three steps has one clear job.

Tracing a Typed Number from the Keyboard

Before reading any code, picture the journey of one number. The user types digits on the keyboard. Those characters arrive at the program through standard input, which Java names System.in. The Scanner object is built on top of that stream, so it can read what arrives there. When your code calls nextInt(), the Scanner takes the next integer from the input and hands it back to the program as an int value. The Scanner variable is the program's access point for input: the user supplies the value, the Scanner variable provides the input operations, and the method produces a value of the requested type.

Keyboarduser types digitsSystem.instandard inputScanner stdininput access pointstdin.nextInt()reads one integerint valuereturned to the programcharacters arriveread bymethod callreturns
Where does the typed number travel from the keyboard, through System.in and the Scanner object, until nextInt() returns it as an int?

Read the diagram from left to right. Notice that the program never touches the keyboard directly. It only talks to the Scanner variable, and the Scanner variable is the one connected to standard input. This is why the variable has to exist before any input method can be called on it.

Where the Import Line Goes

Scanner is defined in the java.util package, so the program must make it available with an import directive. The import directive belongs at the beginning of the source file, before the public class declaration. The statement that creates the Scanner variable is different: it belongs at the beginning of main(). The diagram below shows the order of these lines in a file.

importjava.util.Scanner;first, before the classpublic class ...class declarationpublic static voidmainstart of main()Scanner stdin = newScanner(System.in);created at top of main()thenthenthen
Where does the import line for Scanner go relative to the class declaration and other lines in the file?

Creating the Scanner Variable

The Scanner variable is created with new Scanner(System.in). The source commonly names this variable stdin, which is a convenient name because it stands for standard input. The name is not required. A different variable name may be used. What matters is consistency: once you create the variable under one name, every input call must go through that same name.

java
Notes on the code
  • Scanner is the type of the variable
  • stdin is the variable name, chosen for standard input
  • new Scanner(System.in) connects the variable to standard input

Once this line has run, the variable stdin is ready to provide input operations. Calling a method such as nextInt() on it is what actually asks the Scanner to read a value.

Reading an Integer with nextInt()

The method stdin.nextInt() reads one integer value. Its result must be stored somewhere or used directly, just like any other method that produces a value. The complete program below ties together the three parts you have seen: the import line at the top of the file, the Scanner variable at the start of main(), and a call to nextInt() that produces an int.

Code walkthrough
import java.util.Scanner;

public class AgeReader {
    public static void main(String[] args) {
        Scanner stdin = new Scanner(System.in);
        System.out.print("Enter your age: ");
        int age = stdin.nextInt();
        System.out.println("Next year you will be " + (age + 1));
    }
}
  1. 1
    import java.util.Scanner; makes the Scanner name known to the compiler. It sits before the class declaration, as the source requires.
  2. 2
    public class AgeReader { opens the class. The file name and class name must match in Java.
  3. 3
    Scanner stdin = new Scanner(System.in); runs first inside main(). It connects a Scanner variable to standard input.
  4. 4
    System.out.print prints a prompt without moving to a new line, so the user types on the same line as the prompt.
  5. 5
    int age = stdin.nextInt(); calls the input method through the stdin variable. The integer the user typed becomes the int value stored in age.
  6. 6
    The final println uses age to compute and print the next year's value. The output shown assumes the user typed 20.
  • Line 1 makes the Scanner class available
  • Line 5 creates the Scanner variable connected to standard input
  • Line 7 calls nextInt() and stores the integer in age
Output
Enter your age: 20
Next year you will be 21

What do you think happens?

If the user types the word abc when nextInt() is waiting for an integer, what do you think happens?

Reveal answer
Answer:

The program crashes. nextInt() does not prompt the user to try again.

The source states that an invalid integer causes stdin.nextInt() to crash rather than prompting for re-entry. Scanner.nextInt() expects an integer, and abc is not one, so the program stops with an error.

Mistakes Beginners Make with Scanner

  • Common mistake

    Placing the import line inside main() or after the class declaration

    What it looks like
    public class AgeReader {
        import java.util.Scanner;
        public static void main(String[] args) { ... }
    }
    Why it fails

    The source says the import directive belongs at the beginning of the source file, before the public class declaration.

    Do this instead

    Put import java.util.Scanner; on the first lines of the file, above public class AgeReader.

  • Common mistake

    Creating the Scanner variable but calling a method on a different name

    What it looks like
    Scanner stdin = new Scanner(System.in);
    int age = scanner.nextInt();
    Why it fails

    The variable was created as stdin, so scanner does not exist. The name must match the variable that was created.

    Do this instead
    Use the same name everywhere: int age = stdin.nextInt();
  • Common mistake

    Assuming the variable name stdin is required

    Why it fails

    The source notes that stdin is a convenient choice but not required. A different name may be used.

    Do this instead

    Choose any valid name, then call every input method through that same name.

  • Common mistake

    Forgetting new Scanner(System.in) and calling nextInt() on a variable that was never connected to standard input

Scanner.nextInt() Compared with TextIO.getInt()

TextIO.getInt() is a single call with no visible setup, and the source describes Scanner as needing a little more setup than that. With Scanner, the program must import the class, create a variable connected to System.in, and then call nextInt() through that variable. The comparison below lists what each approach asks you to write. The source does not describe how TextIO.getInt() behaves on invalid input, so this article does not state that behavior. Check the TextIO documentation before relying on it.

TextIO.getInt()one call to read an integerimportjava.util.Scanner;top of the fileNo separate variableshownthe call itself is theinputScanner stdin = newScanner(System.in);top of main()stdin.nextInt()reads one integer, crasheson bad input
How do nextInt() and TextIO.getInt() differ in what they read, what they return, and how they handle invalid input?

Practice Reading an Integer

EASY

Write a complete Java program that asks the user for a number of apples, reads it with Scanner, and prints the number of apples doubled. Your program must include the import line in the correct position, create a Scanner variable connected to System.in, and use nextInt() through that variable.

Hints
  • Start the file with import java.util.Scanner; before the class line.
  • Create the variable at the start of main() with Scanner stdin = new Scanner(System.in);
  • Store the result of stdin.nextInt() in an int variable, then print the doubled value.

Key Takeaways

  • Scanner is a standard Java alternative to TextIO for user input, and it needs a little more visible setup than a single TextIO call.
  • The import directive for Scanner goes at the beginning of the source file, before the public class declaration, because Scanner is defined in java.util.
  • Scanner stdin = new Scanner(System.in); creates the variable at the beginning of main(), and the name stdin is convenient but not required.
  • stdin.nextInt() reads one integer, and an invalid integer makes the program crash rather than prompt again.
  • TextIO.getInt() is a single input call, while Scanner separates the import, the variable, and the method call into distinct steps.