Java program using Scanner Class



Scanner Class in Java

The scanner is a class in java.util package used for obtaining the input of the primitive types like int, double, etc. and strings. It is the easiest way to read input in a Java program, though not very efficient if you want an input method for scenarios where time is a constraint like in competitive programming.

  • To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream. We may pass an object of class File if we want to read input from a file.
  • To read the numerical values of a certain data type XYZ, the function to use is nextXYZ(). For example, to read a value of type short, we can use nextShort()
  • To read strings, we use nextLine().
  • To read a single character, we use next().charAt(0). next() function returns the next token/word in the input as a string and charAt(0) funtion returns the first character in that string

Program to calculate

import java.util.Scanner; //Calling Scanner class

public class Arithmetic

{

     public static void main(String []args)

    {

           double num1, num2, sum, prod, div; // Declaring Variables

           Scanner value= new Scanner(System.in); //Creating object for Scanner class

           System.out.println(“Enter first number”);

           num1= value.nextInt(); //Getting value from keyboard

           System.out.println(“Enter second number”);

           num2= value.nextInt(); //Getting value from keyboard

           sum= num1+num2; //Calculating sum

           prod= num1*num2; //Calculating Product

           if (num1>num2) //Condition to check which number is greater

           {

                 div= num1/num2;

           }

           else

           {

                  div= num2/num1;

            }

             //Displaying result

            System.out.println(“Entered number are “+num1+” and “+num2);

            System.out.println(“Sum = “+sum);

            System.out.println(“Product = “+prod);

            System.out.println(“Division = “+div);

    }

}

Output of the above program is:

         Enter first number

8 Enter second number 4 Entered number are 8.0 and 4.0 Sum = 12.0 Product = 32.0 Division = 2.0



Leave a comment