Java Basic Knowledge (1) : Get Input From User Using Scanner

Welcome to mil-notes. 
Today I'm going to talk about a basic knowledge in java programming: How to get input from user using scanner. Well there are many ways to get input from user in java. But, today I will show to You how to do it with scanner.

To get input in java with scanner we need this: Scanner. It's located in java.util. So, import it before you use it. To import, type this code in the very beginning of your source code.

import java.util.Scanner

After that, create a class "InputWithScanner" with main method in it.

class InputWithScanner{
   public static void main(String[] args){
   }
}

Then, we need a variable to store an input from user. In this tutorial I will use three different variable: int, float, and String. So, write these code inside main method:

int Input1;
float Input2;
String Input3;

After we create some variable to store some input from user, then we create a new object from Scanner. type these code inside main method:

Scanner getInput = new Scanner(System.in);

Finally, we can use getInput object to get an Input from user. Because we use three different variable to store input from user, so we also need some methods from Scanner class. There are:

  1. nextInt to get an Input in integer.
  2. nextFloat to get an Input in float.
  3. nextLine to get an Input in String.

To use that methods, type these code in main method:

System.out.print("Enter a string: ");
Input3 = getInput.nextLine();
System.out.println("You entered string: "+Input3+"\n");

System.out.print("Enter an integer: ");
Input1 = getInput.nextInt();
System.out.println("You entered integer: "+Input1+"\n");

System.out.print("Enter a float: ");
Input2 = getInput.nextFloat();
System.out.println("You entered float: "+Input2+"\n");


So, a complete code will look like this. Save it with name "InputWithScanner.java" (make sure there is no difference between class name and file name)















To execute, we need to compile it first. Open your Command Prompt / terminal and go to where You save the source code. To compile, type these command: 

javac InputWithScanner.java









If there's no error, that mean your source code are good and compiled very well. Then you can move to the next step. Execute!

Type these command in same location where you compile Your source code:

java InputWithScanner 

The output must be like this.











Interesting enough, right?. With this tutorial, You should be able to create a java program to handle and store an input from user. After we can handle and store an input, what's next?. 

- FIN - 




[DOWNLOAD SOURCE CODE]

  1. InputWithScanner.java

Comments