In this lab, you will learn how to handle user input in Java through the console using the Scanner
class. Console input is a fundamental skill in programming, as it allows your Java programs to interact with users by accepting data at runtime. You will use the Nano editor in a Linux environment to write a Java program that takes user input, processes it, and displays the result.
By the end of this lab, you will be able to:
Scanner
class to read input from the console.cd ~
ConsoleInput.java
using the Nano editor:nano ConsoleInput.java
import java.util.Scanner;
public class ConsoleInput {
public static void main(String[] args) {
// Create a Scanner object to read input
Scanner scanner = new Scanner(System.in);
// Prompt the user for their name
System.out.print("Enter your name: ");
String name = scanner.nextLine();
// Prompt the user for their age
System.out.print("Enter your age: ");
int age = scanner.nextInt();
// Display the input back to the user
System.out.println("Hello, " + name + "! You are " + age + " years old.");
}
}
CTRL + O
, then hit Enter
to confirm the filename.CTRL + X
.javac
command:javac ConsoleInput.java
ConsoleInput.class
. Verify this by running:ls
java
command:java ConsoleInput
Enter your name: John
Enter your age: 25
Hello, John! You are 25 years old.
ConsoleInput.java
file again using Nano:nano ConsoleInput.java
System.out.print("Enter your favorite color: ");
String color = scanner.next();
// Display the additional input back to the user
System.out.println(name + ", you are " + age + " years old and your favorite color is " + color + ".");
javac ConsoleInput.java
java ConsoleInput
System.out.print("Enter your height in meters: ");
double height = scanner.nextDouble();
// Display the height back to the user
System.out.println("You are " + height + " meters tall.");
javac ConsoleInput.java
java ConsoleInput
try-catch
blocks..class
files:rm *.class
In this lab, you learned how to use the Scanner
class to accept user input from the console in Java. You wrote a program that prompts the user for their name, age, and other information, processes this input, and displays it back to the user. You also explored handling different data types such as strings, integers, and floating-point numbers. Handling user input is an essential aspect of making your Java programs interactive and dynamic.