Wednesday, January 27, 2021

scanner in java


Scanner in java

 To understand Scanner in java and start using it we have to know some principles

  • The Scanner class is used to get user input
  • Scanner is found in the java.util package
  • To use scanner we have to make an object from scanner class
In other we if we want to use scanner we have to make and object for it , and to make and object for it first we have to import it first , so let us to do this in a code

1/ import scanner 

    import java.util.*;   Or
    import java.util.Scanner;

2/ make object for scanner

    as we know the rule to make an object for any class is 

    class_name object_name = new class_name();
    
    and to create scanner object we can do it as bellow

    Scanner scan = new Scanner(System.in);
    
    scan is the object name , system.in to define that we will read some values form the user

3/ use the scanner to get variable's value from the user

    we can define the variable and then get it's value from the user as bellow

    EG :
        int num;
        num = scan.nextInt();

    or define a variable and get it's value from the user in one line as bellow

    EG : 
        int num = scan.nextInt();

    *Note
 
     we can define (byte , short , long , int , double , float , boolean) with scanner as bellow
 
    byte variable_name = scan.nextByte();
    short variable_name = scan.nextShort();
    int variable_name = scan.nextInt();
    long variable_name = scan.nextLong();
 
    double variable_name = scan.nextDouble();   
    float variable_name = scan.nextFloat(); 
 
    boolean variable_name = scan.nextBoolean(); 
 
and we can (define char , string ) variables as bellow 
      
    Char
 
    char variable_name = scan.next().charAt(0);  Or  
    char variable_name = scan.nextLine().charAt(0);
 
 
    String
 
    String variable_name = scan.nextLine(); Or
    String variable_name = scan.next();  

No comments:

Post a Comment

Odoo Invoice Qr code issues

There are two main issues must of us facing with the QR code in Odoo invoice & these issues are 1/ QR code displayed as broken image w...