Reading a line with Scanner
So far the programs printed the same thing every time. Most programs also take input: something the user types. In Java, a Scanner reads it. Using one takes three pieces:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Write a message:");
String message = scanner.nextLine();
System.out.println(message);
}
}
Hello thereWrite a message:
Hello thereimport java.util.Scanner;at the very top tells the compiler where the Scanner comes from. Scanner is part of Java's standard library, in the packagejava.util, and a program has to import it before using it.Scanner scanner = new Scanner(System.in);creates a Scanner calledscannerthat reads fromSystem.in, the program's input. One Scanner is enough for the whole program.String message = scanner.nextLine();waits until the user has typed a line and pressed Enter, then keeps that line inmessage. The next step explains whatString messagemeans.
Input on this site
When you run a program in a terminal, you type the input while it runs, and your typing appears on the screen between the program's lines. The checks here give the program all of its input at the start instead, like a pre-typed answer sheet, so the expected output only contains what the program itself prints. That's why Hello there appears once in the output above, not twice.