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.
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:
Note: After clicking the “Run” button below, click anywhere inside the black terminal window. When you see a blinking cursor, you’ll know that the program is waiting for your input. Use your keyboard to write anything and then press enter. Give it a shot:
import java.util.Scanner; public class MyJavaApp { public static void main(String[] args) { Scanner scan = new Scanner(System.in); scan.nextLine(); } }
Line 1 imports the Scanner
class package for us. Line 6 is ...