Skip to main content
Engineering LibreTexts

11.2: The Scanner Class

  • Page ID
    15222
  • The System class also provides the special value System.in, which is an InputStream that provides methods for reading input from the keyboard. These methods are not easy to use; fortunately, Java provides other classes that make it easier to handle common input tasks.

    For example, Scanner is a class that provides methods for inputting words, numbers, and other data. Scanner is provided by java.util, which is a package that contains classes so useful they are called “utility classes”. Before you can use Scanner, you have to import it like this:

    import java.util.Scanner;
    

    This import statement tells the compiler that when you say Scanner, you mean the one defined in java.util. It’s necessary because there might be another class named Scanner in another package. Using an import statement makes your code unambiguous.

    Import statements can’t be inside a class definition. By convention, they are usually at the beginning of the file.

    Next you have to create a Scanner:

    Scanner in = new Scanner(System.in);
    

    This line declares a Scanner variable named in and creates a new Scanner that takes input from System.in.

    Scanner provides a method called nextLine that reads a line of input from the keyboard and returns a String. The following example reads two lines and repeats them back to the user:

    import java.util.Scanner;
    
    public class Echo {
    
        public static void main(String[] args) {
            String line;
            Scanner in = new Scanner(System.in);
    
            System.out.print("Type something: ");
            line = in .nextLine();
            System.out.println("You said: " + line);
    
            System.out.print("Type something else: ");
            line = in .nextLine();
            System.out.println("You also said: " + line);
        }
    }
    

    If you omit the import statement and later refer to Scanner, you will get a compiler error like “cannot find symbol”. That means the compiler doesn’t know what you mean by Scanner.

    You might wonder why we can use the System class without importing it. System belongs to the java.lang package, which is imported automatically. According to the documentation, java.lang “provides classes that are fundamental to the design of the Java programming language.” The String class is also part of the java.lang package.

    • Was this article helpful?