Tuesday, April 6, 2021

thumbnail

why we need to take user input using scanner

                    Most of time we need to take input from users. why we need to take input from user. is it important ? Yes , it is important because I will explain by one example . let me allow,

           we will write one simple program adding a two numbers. Two numbers are input for  code.  please refer below code snippet. we did hard code like a = 10 and b = 20,  

                  suddenly we need to change means input value. Again go to code and change the variable value. it seems easy for one or two times. n times need to change. it is very difficult to do. So we will take input from user .  user can give any input . code should be work and it should give correct output. That sounds good. so we will use scanner class .

  Code bit : Add two number in Java

Add Two Number in Java
Result






 Scanner class will help us to take input from user. it is present in Javautil  package. 

Let's see code 

In the code, we will take two integer number by user Using Scanner 

Steps :

  • Create scanner object 
  • Take first number  from user (Console) using scanner 
  • Take second number from user (Console)
  • Additional logic 
  • Display the result 


Scanner in Java

import java.util.Scanner;

public class ExampleScanner {

public static void main(String[] args) {
   Scanner sc = new Scanner(System.in);
   // Taking number from User
       System.out.println("Enter first number : " );
         int a =  sc.nextInt();
       // Taking number from User
       System.out.println("Enter second number : " );
         int b =  sc.nextInt();
        // Adding 
        int c = a + b;
        // Printing number
        System.out.println("The result is :"+ c);
        }
}


Result :



Leant Things : 
  • Scanner Object - it is used for taking user input. 
  • we need to import scanner from java.util.Scanner;
  • Creating scanner object like  Scanner sc = new Scanner(System.in);
  • nextInt() - this method is used for taking int type values from user
we learn only taking int value from user.  we will see upcoming blogs other codes snippet which will take float, double, etc datatypes and string as input  using scanner.



                                      Thank You :)

Sagar R G     
Java Developer 



Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

FullStackDeveloper. Powered by Blogger.