Scanner

6 0 0
                                    

Scanner is an API class translator that uses a token as a concept and separate each token using a whitespace by default. A token is a small part taken from something big as a souvenir. So, the Scanner class takes a word from your whole message treating each word as a token and translate it according to its type.

syntax:

Scanner objectName = new Scanner(System.in)

     - objectName is an instance that we create from a Scanner class to access its properties and functions.

     - System.in parameter means we want to accept a keyboard input.

================

class ScannerPractice{

    public static void main(String[] args){

        Scanner input = new Scanner(System.in);

        System.out.print("Enter name: ")

        String name = input.next();

        System.out.println("Your name is " + name);

    }

}

================

Result:

Enter name: Albert Einstein

Your name is Albert

Note: Here you input Albert Einstein. It is two tokens from Scanner perspectives. It did read both but just display the first token.

=================

class ScannerPractice{

    public static void main(String[] args){

        Scanner input = new Scanner(System.in);

        System.out.println("Enter anything or 999 to stop:");

        while(input.hasNext()){

            String str = input.next();

            System.out.println("input: " + str);

             if(str.equals("999")){

                 break;

             }

        }

        input.close();

    }

}

=================

Result:

Enter anything or 999 to stop:

Albert Einstein

input: Albert

input: Einstein

999

input: 999


Note: Since Scanner class can translate all tokens according to its type, you can use this to your advantage. For example, Scanner class has the function hasNext(), hasNextDouble(), and so on. Just checked out the others.

Java ProgrammingWhere stories live. Discover now