How to Prompt for an Answer in Java
- 1). Load the NetBeans IDE by clicking on its program icon. When the program loads, navigate to "New/New Project" and select "Java Application" from the list on the right side of the screen. A new source code file appears in the NetBeans text editor. The source code file contains an empty main method.
- 2). Import the "java.io" module by writing the following at the top of the source code file:
import java.io.*; - 3). Create a new "BufferedReader" object that will read the answer typed in by the user. To declare a "BufferedReader" object, write the following statement within the curly brackets of the main method:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); - 4). Print out the question you would like to ask. Write something similar to the following statement and place it below the statement typed in on the previous step:
System.out.println("What is your name?"); - 5). Create a prompt using the "readLine" method of the "BufferedReader" object. You can store the answer in a variable by writing the following statement:
String name = in.readLine(); - 6). Print out a response to the question like this:
System.out.println("Hello " + name); - 7). Execute the program by pressing "F6." The program prompts you for your name. Enter your name at the prompt. The program then says "Hello" followed by the name you typed in.
Source...