User Input
Last updated
Last updated
Being able to obtain user input creates new opportunities while coding. This allows us to take in data from the user to make our programs work for them.
In Java there are four ways we can obtain user input:
To read the user's input as a string, we usereadLine("String prompt")
. This allows us to ask the user for their name, favorite color, or any other text input from the user.
Here is an example of how we would ask the user for their favorite color, and then print it:
To read the user's input in an integer format, we usereadInt("String prompt")
. This allows us to ask the user for their age, favorite number, or any other whole number.
Here is an example of how we would ask the user for their age, and then print it:
To read the user's input as a double, we usereadDouble("String prompt")
. This allows us to ask the user how many miles they have traveled, how much an item costs, or any other numerical value that has a decimal.
Here is an example of how we would ask the user for how many miles they have traveled, and then print the input:
To read the user's input as a boolean, we usereadBoolean("String prompt")
. This allows us to ask the user any true or false question.
Here is an example of how we would ask the user if they are a astronaut, and then print their answer:
Now that we have seen a some examples of how to get user input, lets look an application.
Lets say we are writing a piece of code in which we want to ask the user for their name, age, and if they own a pet. In this case we will ask the user each question, one at a time, and store the answers in their own variables. After we get the user input we will print the variables. Here is what our code will look like:
Here is what the user prompts will look like, once the code executes: