Certainly! Below is a simple Java program that prompts the user to enter their name and the state they live in, and then prints out a formatted message using the provided information.
import java.util.Scanner;
public class UserInfo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Ask the user for their name
System.out.print("Please enter your name: ");
String name = scanner.nextLine();
// Ask the user for their state
System.out.print("Please enter the state you live in: ");
String state = scanner.nextLine();
// Print the formatted message
System.out.println("My name is " + name + ". I live in " + state + ".");
// Close the scanner
scanner.close();
}
}
Explanation:
- This program uses
Scanner
from thejava.util
package to read input from the user. - It prompts the user to enter their name and the state they live in.
- It stores the input in the
name
andstate
variables, and then prints the formatted message using those variables. - Finally, it closes the
Scanner
resource.
How to Run:
- Copy the code into a file named
UserInfo.java
. - Compile the code with
javac UserInfo.java
. - Run the program with
java UserInfo
. - Follow the prompts to enter your name and state. The output will be displayed as specified.