User Inputs

Sometimes we create a program for user to use it. Therefore, we need the program to read the user input. In Java, we use Scanner object to scan for user input and store it in a variable. To use the Scanner object, you need to import scanner function from utility (util) library first.

  1. How to import the Scanner function from utility library?

    import java.util.Scanner;

    Add the above line of code in between the package and public class.

  2. How to use the Scanner to read the user input and store it in a variable?

    Scanner scan = new Scanner(System.in);

    System.in – Reading the user input from keyboard.
    Scanner scan = New Scanner(); – the system input will be assigned and stored to a Scanner object named scan.

  3. Make sure that the user provide the necessary input before the program continues to run. Therefore, we need the nextLine() to make sure the program pause till the input is given.

    System.out.println(scan.nextLine());

    nextLine() – is used for String inputs. If the input is integer, use nextInt().

userInput
User Input codes

Leave a comment