Java program to get inputs from user using Scanner Class

Java program to get inputs from user :

In this example , we will see how to get inputs from a user. We will use the ‘Scanner’ class to get the inputs. We will scan one String, one int and one float.

First we are creating one ‘Scanner’ object . Constructor to creat this object is ‘Scanner(InputStream source)‘. That is we need to pass one ‘InputStream’ to create the ‘Scanner’ object. We are passing ‘System.in’ as an argument which is the ‘standard’ input stream . Means , if user is entering input on the terminal, ‘Scanner’ object will read it.

Example Java Program :

import java.util.Scanner;

public class Main {


    static void print(String string) {
        System.out.println(string);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        print("Enter a string : ");
        String line = scanner.nextLine();
        print("You have entered " + line);

        print("Enter a int : ");
        print("You have entered " + scanner.nextInt());

        print("Enter a float : ");
        print("You have entered " + scanner.nextFloat());

    }
}

Output :

Enter a string : 
Hello World
You have entered Hello World
Enter a int : 
12
You have entered 12
Enter a float : 
12.33
You have entered 12.33

Useful methods of Java Scanner class :

String next() : Finds and returns the next complete token from the Scanner. BigDecimal nextBigDecimal() : Scan the next input as BigDecimal . BigInteger nextBigInteger() : Scan the next input as BigInteger . boolean nextBoolean() : Scan the next input as a boolean value . byte nextByte() : Scan the next input as a byte value . double nextDouble() : Scan the next input as Double . long nextLong() : Scan the next input as Long . short nextShort() : Scan the next input as short .

Similar tutorials :