Java User Input

We already learned java variables and data types, Java initialization, and java format specifiers. We know how to print them out. Now, if we say to ask the user to save some information for you and print them out later? Yes, we are talking about the java User input. But before you jump into this section, we will recommend you to have a revision to those contents. Hence, you will not get confused in some places we are going to discuss here.

User input in Java helps the operator to scan and store the value given by the operator. Let’s demonstrate an example so that you can easily understand this Java user input. In the following first have a look at the program. And then check out the output picture. After that, continue reading. We have explained the code at the below. 

Taking input in Java

Establish a java code where the compiler will save your entered value and send you as output.

Solution: The java code is as followed:

package main;
import java.util.Scanner;
public class First{
    public static void main( String args[] ) {
 System.out.printf("Please enter your number: ");
 Scanner input = new Scanner(System.in);
 int num = input.nextInt();
 System.out.printf("You entered %d , right?%n", num );
 System.out.println("That's how a user input works");
 } }

Output:

Java User Input

Using scanner in java

From the mentioned code above, first, You must import java.util.scanner. Why? Because if you want your compiler to scan your command and store it, you must import the java.util.scanner. And then, using printf, we sent output to the terminal. “Please enter your number.” You can use println / print. We used printf because you wat our input cursor on the same line of the sentence.

The next section is significant. To scan the entered value, we first wrote  Scanner input = new Scanner(System.in). Finally, to store the value we used int num = input.nextInt().And then, we went through the procedure to take out the entered value. We used the printf function with the format specifier.

There are more examples related to Java user input are here in infolinux. What you need to do is plan your time and learn all of it effectively.   

Leave a Reply