Introduction
This is a simple tutorial on using the Scanner class in Java. The Scanner class lets you accept input from the console. The user types on the keyboard and passes that data to the program.
Prerequisites
- Install Java and Visual Studio (VS) Code. Here is a tutorial: Tutorial: Visual Studio Code and Java.
- Start VS Code.
- Create a new Java project as specified in the tutorial.
- In the left sidebar, right-click the
src
folder and select New File. Create a file namedExample.java
. - Continue to the tutorial below.
Code
In the left sidebar in VS Code, click the Example.java
file to show it in the main editor window. Enter this initial code:
public class Example {
public static void main(String[] args) {
}
}
To use the Scanner class, import it at the top of the program:
import java.util.Scanner; // NEW
public class Example {
public static void main(String[] args) {
}
}
Next, create a Scanner object to read from standard input (i.e., the console):
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner s = new Scanner(System.in); // NEW
}
}
Now prompt the user to enter some data from the keyboard:
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("What is your favorite number? "); // NEW
}
}
Use the Scanner object to accept an integer value from standard input and assign it to a variable:
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("What is your favorite number? ");
int num = s.nextInt(); // NEW
}
}
The num
variable holds the input data. Output the num
variable to verify:
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("What is your favorite number? ");
int num = s.nextInt();
System.out.println("Your favorite number is: " + num); // NEW
}
}
Here is a sample run of the program from the terminal:
What is your favorite number? 44
Your favorite number is: 44
Additional Exercise
- Modify the program to ask the user for an age and day of the month.
- Output the age and day of the month.
Thanks for reading.
Follow me on Twitter @realEdwinTorres
for more programming tips. 😀
Top comments (0)