Java Exercise
In this exercise, you will create a Java program that reads user input and displays it to the console. You will use the System.out.println()
method to print messages and the Scanner
class to read user input from the console. You will learn how to capture different types of data, such as numbers and text, and how to process them within your program.
Instructions:
- Declare a variable of type
Scanner
to read user input.
- Prompt the user to enter their name and store the input in a variable of type
String
.
- Prompt the user to enter their age and store the input in a variable of type
int
.
- Use
System.out.println()
to print the user's name and age.
- Compile and run the program to see the output in the console.
This exercise will help you understand how to interact with the user using Data Input and Output in Java, an essential step in developing interactive applications.
View Example Code
import java.util.Scanner;
public class InputOutputData {
public static void main(String[] args) {
// Create a Scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Ask the user to enter their name
System.out.print("Enter your name: ");
String name = scanner.nextLine();
// Ask the user to enter their age
System.out.print("Enter your age: ");
int age = scanner.nextInt();
// Display the entered information on the console
System.out.println("Your name is: " + name);
System.out.println("Your age is: " + age);
// Close the Scanner object
scanner.close();
}
}
Output:
Enter your name: John
Enter your age: 25
Your name is: John
Your age is: 25
This code shows how to use the Scanner
class to read user input, such as their name and age, and then print that data to the console using System.out.println()
.