Asking the user for input
So far our programs always print the same thing. To make them react to the user, we read input with a tool called Scanner.
Think of it like this: Scanner is like a waiter taking your order. You tell it what kind of thing to listen for (a number? a word?) and it brings that back to your program.
Using Scanner takes three steps:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("What is your name?");
String name = sc.nextLine();
System.out.println("Hello, " + name + "!");
}
}Input (what the user types)
Priya
Output
What is your name? Hello, Priya!
import java.util.Scanner;– at the very top: “I want to use Scanner”.Scanner sc = new Scanner(System.in);– make a scanner that reads the keyboard (System.in).sc.nextLine()– wait for the user to type a line, and give it back as a String.
Reading different types
| Method | Reads | Gives back |
|---|---|---|
sc.nextInt() | a whole number | int |
sc.nextDouble() | a decimal number | double |
sc.next() | one word (stops at a space) | String |
sc.nextLine() | the whole line, spaces included | String |
sc.nextBoolean() | true or false | boolean |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println(a + " + " + b + " = " + (a + b));
}
}Input (what the user types)
7 5
Output
7 + 5 = 12
nextInt() skips spaces and new lines, so the two numbers can be on one line (7 5) or on two lines.
The nextInt + nextLine trap
nextInt() reads the number but leaves the Enter key behind. A nextLine() right after it reads that empty leftover instead of the next line:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
sc.nextLine(); // throw away the rest of the age line
String city = sc.nextLine();
System.out.println(age + " years old, from " + city);
}
}Input (what the user types)
25 New Delhi
Output
25 years old, from New Delhi
Common mistake: If you mix
nextInt()andnextLine(), add an extrasc.nextLine();after the number to clear the rest of the line.