Hi, In this post we will discuss how to get input from the keyboard at run-time in java. For this task we use the Scanner class from java.util.Scanner package.



import java.util.Scanner;

First of all import the Scanner class in our project using the above code.


Scanner scan =  new Scanner(System.in);

Create an object scan(you can give any name either of scan) of the Scanner class, which used to call a method from the Scanner class.


int a = scan.nextInt();

In the above-given code, we use the method with the help of a scan object that takes integer type data from the user keyboard for different data we use a different method of Scanner class.


Method of Scanner Class

next()
Finds and returns the next complete token from this scanner.


nextBoolean()
Scans the next token of the input into a boolean value and returns that value.

nextByte()

Scans the next token of the input as a byte.

nextDouble()

Scans the next token of the input as a double.

nextInt()
Scans the next token of the input as an int.

nextFloat()
Scans the next token of the input as a float.

nextLong()
Scans the next token of the input as a long.

nextShort()
Scans the next token of the input as a short.

Program to Sum of two number from user input

import java.util.Scanner;

class Main{
    public static void main(String [] aa){
        Scanner sc = new Scanner(System.in);
        System.out.println("enter value of a ");
        int a = sc.nextInt();
        System.out.println("Enter Value of b ");
        int b = sc.nextInt();
        System.out.println("Sum of a and b " + (a+b));
    }
}

Output
    enter value of a 50
    Enter Value of b 40
    Sum of a and b 90


if you face any type of problem then you can contact us by comment section.


Post a Comment

Previous Post Next Post