AI Hints
Home›Java Tutorial›Reading Input with Scanner, Reading Numbers, Practice: A Receipt
Java · Lesson 25 of 120

Reading Input with Scanner

Talk to your program.

⏱ 2 min read▶ Video at 32:52🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

So far, our programs always do the same thing. Reading input lets the person using the program type something, and the program reacts to it.

  • Programs that listen
  • Type an answer
  • The program reacts

What you need

Scanner is a class that reads input. It lives in a package called java dot util, so we import it, at the very top. We create one Scanner, connected to System dot in, the keyboard. Then next line reads one line of text.

keyvalue
importjava.util.Scanner
Createnew Scanner(System.in)
System.inthe keyboard
nextLine()reads a line of text

Asking questions

Import makes Scanner available. We create a Scanner, called in. Print asks the question, without a new line, so the answer appears right after it. Next line waits, until the user presses enter, then gives back what they typed. Run it. Here, someone typed Maya, and green.

Main.javajava
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("What's your name? ");
        String name = in.nextLine();
        System.out.print("Favourite colour? ");
        String colour = in.nextLine();
        System.out.println("Hi " + name + "! " + colour + " is a great colour.");
    }
}
Input typed: Maya · green
Output
What's your name? Maya
Favourite colour? green
Hi Maya! green is a great colour.

Summary

Import Scanner, create one on System dot in, and call next line to read a line of text. Next, reading numbers.

Key takeaways
  • import java.util.Scanner
  • new Scanner(System.in)
  • nextLine()
Next up: Reading Numbers — nextInt and nextDouble