Java provides many different methods to get input from the user. The one we are going to study here is by using the Scanner class. The first thing we will have to do is to import the scanner class. To import the scanner class, you will have to write the code at the place you can see in the screenshot below.
After this, you will be coding in the main method as you did before. First thing you will have to do is to create a new scanner object. This is done as:
The anyName in the above statement is the name for the Scanner. The rules for choosing this name are same as you studied in the previous lessons about naming a variable. For example, I am naming it in. It will now look like following:
There are different methods available in the scanner class to take inputs of different data types. These methods are:
Read a byte: nextByte()
Read a short: nextShort()
Read an int: nextInt()
Read a long: nextLong()
Read a float: nextFloat()
Read a double: nextDouble()
Read a boolean: nextBoolean()
Read a complete line: nextLine()
Read a word : next()
We will direct the input from the user into a variable. Let’s take an example on how to input an integer from the user. Keeping in mind the above format, our nameOfScanner is in and methodName() is nextInt(). So it will look like following:
Let’s take an example of a program that inputs a number from the user and displays it on the screen.
When you run this program, it will wait for your input in the output section of the program.
Now let’s take an example of a program that takes two numbers as input and displays their sum on the screen.
Display input message:
To make your program user friendly, it is advisable to display a message on the screen which tells the user that the program is demanding an input. For this we can use System.out.print(); statement. The difference between System.out.println(); and System.out.print(); is that the System.out.println(); statement covers a whole line whereas the System.out.print(); statement does not use the whole line and leaves the space for the user to type the input on the same line. Let’s modify the above program to make it user friendly.
*We used the concatenation operator ( + ) in the last System.out.println(); statement to display text and numbers next to each other.
Let’s take an example of another program that inputs a String.
Practice Corner:
- Write a program to input the length and width of a rectangle and display its area and perimeter on the screen. The program should be user friendly.
- Write a program that inputs the radius of a circle from the user in a user friendly manner and displays its circumference and Area on the screen.
- Write a program to input celsius temperature from the user and display its equivalent fahrenheit temperature on the screen.