Scanner class



What is Scanner class ?

  • This is a one of methods that can be used to get user inputs in a program.
  • There are various types of user inputs. They may be int, double, float, char, String...etc.
  • So this is very important thing in Java programming.
  • Scanner is not safe for multithreaded use without external synchronization. 

How to use Scanner class ?

  • Scanner class belongs to java.util.Scanner class.
  • You have to import it. (Not like String class)
               import.java.util.Scanner;

  • Above statement import the Scanner class or you can import whole util package like below.(' * ' symbol define whole)
               import.java.util.*;

  • After you import it, user can input inputs either using keyboard or using file. 
  • But you have to create Scanner object.

    Creating Scanner objects

    • Instead of creating int, char or other types, we are creating scanner type objects.
    • You have a great knowledge about, how to create objects and constructors.
    • It is mostly like creating other objects(String, StringBuffer, StringBuilder). But there is something different. 
                         Scanner scn = new Scanner(System.in);

    • This is the Scanner constructor that provide inputs of specified input stream(That is why we used System.in).
    • scn is a Scanner type reference variable.
    • In above statement there is something called System.in, This is used to specify that will be a system input.
    • There can be other types also. I mention few of them.
                     Scanner(file resource) - Scan values from specified file
                     Scanner(readable resource) - Scan values from specified source
                     Scanner(string resource) - Scan values from specified string

    How do Scanner work ?

    • Now you have created Scanner types variable(scn).
    • This variable can hold the value that you have input using Scanner.
    • Then we have to place that value in memory(heap).
    • To do that, we have to define a reference variable to refer the value  entered above by user.
    • It means, if you want to handle String type of data(name,city), you have to define String variable. If you want to handle int type data(id,age), you have to define int type variable.

    scn just hold the value of user input

    scn.next() is put in the heap by s

    • It can be done as follows. 

    import java.util.Scanner;
    public class ScannerTest {
            public static void main(String args[]){
      
                    Scanner scn = new Scanner(System.in);
                    System.out.print("Please enter your name: ");
      
                    String s  = scn.next();
      
                    System.out.println("Your name is " + s);
            }
    
    }
    
    
    
    In this program I want to get the user name. It is a String type one. So I define a String type variable called 's'. Then I assign scn.next() to the variable s. WHAT IS THIS NEXT() ?


    Scanner class methods

    Like other classes Scanner class also have set of methods(More than 50). You need to understand few of them if you wand to ready to OCPJP 6 1Z0-851 examination. Without these methods we cannot assign a memory space using reference variable. In above example I have used next() method. Below I mention few special methods in Scanner class.

    next()
    This method finds and return the next complete token from Scanner. Receives the next token from scanner object as a String. 

    int nextInt()
    This method finds and returns the next token from Scanner as an int.

    float nextFloat()
    This method finds and returns the next token from Scanner as an float.

    long nextLong()
    This method finds and returns the next token from Scanner as an long.

    double nextDouble()
    This method finds and returns the next token from Scanner as an double.

    String nextLine()
    This method receives the next line of the String.

    Scanner reset()
    This method resets the Scanner.

    void close()
    This method close the Scanner.

    Boolean hasNextInt()
    Returns true if the next token in the Scanner object can be interpreted as an int value.

    Boolean hasNextDouble()
    Returns true if the next token in the Scanner object can be interpreted as an double value.

    Boolean hasNextFloat()
    Returns true if the next token in the Scanner object can be interpreted as an float value.

    Boolean hasNextLong()
    Returns true if the next token in the Scanner object can be interpreted as an long value.

    Boolean hasNext()
    Returns true if the next token in the Scanner has another token in its input.

    Boolean hasNextLine()
    Returns true if there is another line in the input of this Scanner.

    Now you can practice these methods. Look at the following example.

    import java.util.Scanner;
    public class ScannerTest {
           public static void main(String args[]){
      
                  Scanner scn = new Scanner(System.in);
      
                  System.out.print("Please enter your name: ");
                  String name  = scn.next();
      
                  System.out.print("Please enter your id: ");
                  int id = scn.nextInt();
      
                  System.out.println("Your name is " + name);
                  System.out.println("Your id is " + id);
          }
    }
    
    

    This is a simple program that asking you to input your name and id. I have used String name for name and int id for id. When you run the program It asks to enter your name and then id. You can see that I used nextInt() method for it. It means you have to provide int type id. What will happen if you enter String type? It will return an exception when you enter it. We talk more about exceptions in later posts. The exception is InputMismatchException. It means the data type you entered is incorrect as to the program.

    This is a simple calculator program. But I didn't handle the exceptions here. You will be learn it later.


    import java.util.Scanner;
    public class ScannerTest {
           public static void main(String args[]){
                  Scanner scn = new Scanner(System.in);
      
                  System.out.print("Please enter number one: ");
                  float num1  = scn.nextFloat();
                  System.out.print("Please enter number two: ");
                  float num2 = scn.nextFloat();
                  System.out.print("Please enter the operator: ");
                  String op = scn.next();
      
                  switch(op){
                    case "+":
                       System.out.println("Result: " + (num1+num2));
                       break;
                    case "-":
                       System.out.println("Result: " + (num1-num2));
                       break;
                    case "*":
                       System.out.println("Result: " + (num1*num2));
                       break;
                    case "/":
                       System.out.println("Result: " + (num1/num2));
                       break;
                    default:
                       System.out.println("Please enter valid numbers.");
                  }
           }
    }
    
    
    

    Try this program to get idea about Boolean methods.


    import java.util.Scanner;
    public class ScannerTest {
            public static void main(String args[]){
      
                  Scanner scn = new Scanner(System.in);
      
                  System.out.print("Please enter number one: ");
                  boolean num  = scn.hasNextInt();
      
                  if(num==true){
                        System.out.println("You have entered an int");
                  }
                  else
                        System.out.println("You entered value is not an int");
                  }
    }
    
    
    

    hasNextInt() method will return true or false. If true it will print something in this program, else print another thing. You can use this to avoid popup exceptions in simple calculator program.







    Scanner class Scanner class Reviewed by Ravi Yasas on 9:15 PM Rating: 5

    No comments:

    Powered by Blogger.