Write a program that will ask the user to enter their name and the state they live in. Print the following sentence, replacing the ______ with the words they entered. My name is _____. I live in _____. in java

1 answer

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 the java.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 and state variables, and then prints the formatted message using those variables.
  • Finally, it closes the Scanner resource.

How to Run:

  1. Copy the code into a file named UserInfo.java.
  2. Compile the code with javac UserInfo.java.
  3. Run the program with java UserInfo.
  4. Follow the prompts to enter your name and state. The output will be displayed as specified.