N. Achyut java User input in java | Understanding about java input types

User input in java | Understanding about java input types

User input in java

In this page you are going to learn about :

  • Reading User input
  • Scanner Class
  • Important Scanner Method

Reading User Input

To read the user input, Scanner class is used with a standard input stream System.in

Scanner Class

  • Scanner class is defined in java.util package
  • Java provides various ways to read input from the keyboard, the java.utl.Scanner class is one of them
  • Scanner class is widely used to parse text for string and primitive types using a regular expression.
  • Scanner breaks its input into tokens using a delimiter pattern

Syntax :

Scanner scanner ojbect = new Scanner(System.in);


Important Scanner Methods

  • nextInt() -> Scans the next token of the input as an int.
  • nextDouble() -> Scans the next token of the input as a double.
  • nextLine() -> Advances this scanner past the current line and returns the input that was skipped
  • next() -> Finds and returns the next complete token from this scanner.
  • nextFloat() -> Scans the next token of the input as a float.
  • hasNext() -> Returns true if this scanner has another token in its input

Example

public class UserInput {

    public static void main(String[] args) 
    {
        Scanner in = new Scanner(System.in);
        //user input for string
        System.out.println("Enter your name:");
        String name = in.next();
        System.out.println("Your name is: "+ name);
        
        //user input for integer
        System.out.println("What is your age?");
        int age = in.nextInt();
        System.out.println("Your age is : " + age);
    
    }
    
}

Full code on github

Related Post