Sub topic 1
Reading Console Input in Java with IO and Scanner
Prerequisites
This chapter assumes basic Java syntax, variables, methods, control flow, and primitive types such as int and double. You should also know how to compile and run a Java program from the command line.
Standard input and `System.in`
Standard input is the stream from which a program receives input. When you run a program in a terminal, standard input normally carries characters typed by the user. Java exposes this stream as System.in.
System.in is an InputStream. It provides raw bytes, so most programs wrap it in a higher-level reader. Scanner is a convenient choice for small console programs.
Creating a `Scanner`
Import java.util.Scanner, then pass System.in to its constructor:
import java.util.Scanner;
public class Greeter {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Name: ");
String name = in.nextLine();
System.out.println("Hello, " + name);
}
}The Scanner reads and converts input for you. Its default delimiter is whitespace, including spaces, tabs, and line breaks.
Reading numbers and words
Use nextInt() for an integer, nextDouble() for a decimal number, and next() for one whitespace-delimited word.
import java.util.Scanner;
public class Order {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Quantity: ");
int quantity = in.nextInt();
System.out.print("Product: ");
String product = in.next();
System.out.println(quantity + " " + product);
}
}These methods wait for input and then convert it. If the next token cannot be converted to the requested type, the scanner reports an input error. Later, validate input before calling conversion methods.
Reading a whole line
Use nextLine() when spaces belong to one value, such as a full name or a sentence.
import java.util.Scanner;
public class Message {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Message: ");
String message = in.nextLine();
System.out.println("You wrote: " + message);
}
}Exercise
Which Scanner method reads an input value that may contain spaces?
Show answer
Use nextLine().