...

/

Input and Assign to Variable

Input and Assign to Variable

Learn to take input from a user and save it for later use.

Taking input from a user

Let’s continue making our way into Java and the project. Notice that project requirements 1 and 5 are categorically different from requirement 2, which is printing something on the screen.

Press + to interact
The project requirements that require printing the output on the screen
The project requirements that require printing the output on the screen

Now we know how to print a name on the screen using Java, but how does our code ask the elementary school student to tell us their name?

The method for input

Just like println prints a line on the screen, what would be the method’s name that scans the next line on the console for input from the user’s keyboard? To do that in Java, we have to place just one tiny block on top of the class block first, while everything else remains the same. This block (shown in blue in the illustration below) is for importing any packages. To be able to scan the next line for the user’s input, we have to import a utility package named Scanner into our code at the very top, and then use the package later in the code. See the slide illustrations below for clarity:

Press + to interact
canvasAnimation-image
1 / 5

Note: After clicking the “Run” button ...

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy