In Java, we can create interactive programs that ask the user to type something and then use that input in our programs. This makes our programs much more useful and engaging.
To read user input, we use the Scanner class, which is part of Java’s standard library.
First, we need to import the Scanner class and create a Scanner object:
import java.util.Scanner;
public class ZipCode {
void compute() {
Scanner scanner = new Scanner(System.in);
// Your code goes here...
scanner.close();
}
public static void main(String[] args) { new ZipCode().compute(); }
}The Scanner object connects to System.in, which represents input from the keyboard (or console).
Always remember to close the scanner when you’re done with it using scanner.close() - this frees up system resources.
The Scanner class provides different methods for reading different types of data:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("You are " + age + " years old.");Scanner scanner = new Scanner(System.in);
System.out.print("Enter your first name: ");
String firstName = scanner.next();
System.out.println("Hello, " + firstName + "!");Scanner scanner = new Scanner(System.in);
System.out.print("Enter your full name: ");
String fullName = scanner.nextLine();
System.out.println("Nice to meet you, " + fullName + "!");Here’s a complete program that demonstrates reading different types of input:
import java.util.Scanner;
public class ZipCode {
void compute() {
Scanner scanner = new Scanner(System.in);
System.out.print("What is your name? ");
String name = scanner.nextLine();
System.out.print("How old are you? ");
int age = scanner.nextInt();
scanner.nextLine(); // consume the leftover newline
System.out.print("What is your favorite number? ");
double favoriteNumber = scanner.nextDouble();
System.out.println("Hello " + name + "!");
System.out.println("You are " + age + " years old.");
System.out.println("Your favorite number is " + favoriteNumber);
scanner.close();
}
public static void main(String[] args) { new ZipCode().compute(); }
}Note: Notice the extra scanner.nextLine() after reading the age. This is needed to consume the "Enter" key that remains after typing a number.
Sometimes users might enter invalid data. Here’s how to handle that:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
if (scanner.hasNextInt()) {
int number = scanner.nextInt();
System.out.println("You entered: " + number);
} else {
System.out.println("That's not a valid number!");
scanner.next(); // clear the invalid input
}Here are the most commonly used Scanner methods:
| Method | Description |
|---|---|
|
Reads the next integer |
|
Reads the next decimal number |
|
Reads the next single word (stops at whitespace) |
|
Reads an entire line of text |
|
Checks if the next input is an integer |
|
Checks if the next input is a decimal number |
|
Checks if there is more input available |
-
Always close your Scanner when you’re done with it using
scanner.close(). -
Be careful with mixing number methods and
nextLine(). After reading a number withnextInt()ornextDouble(), callscanner.nextLine()to consume the leftover "Enter" key press. -
Handle invalid input by checking with
hasNextInt()or similar methods before reading. -
Only create one Scanner object per program that reads from
System.in.
Try creating a program that asks for user information:
import java.util.Scanner;
public class ZipCode {
void compute() {
Scanner scanner = new Scanner(System.in);
// Ask for name
System.out.print("What is your name? ");
String name = // Your code here
// Ask for age
System.out.print("How old are you? ");
int age = // Your code here
// Don't forget the nextLine() after reading a number!
// Ask for favorite color
System.out.print("What is your favorite color? ");
String color = // Your code here
// Print personalized message
System.out.println("Hi " + name + "! You are " + age + " years old and you like " + color + ".");
scanner.close();
}
public static void main(String[] args) { new ZipCode().compute(); }
}Problem: Program skips asking for input or gives unexpected results.
Solution: Make sure to call scanner.nextLine() after using nextInt() or nextDouble().
Problem: Program crashes when user enters wrong type (like letters when expecting numbers).
Solution: Use validation methods like hasNextInt() before calling nextInt().
This is a fundamental skill in Java programming that makes your programs interactive and user-friendly!