Menu
Topics Index
...
`

Instantiating a Scanner object by passing a String as parameter - Java Example Program


Instantiating a Scanner object by passing a String as parameter
import java.util.Scanner;

class ScannerConstructorDemo2
{
    public static void main(String arg[])
    {
        String str = "Germany are the champions";
                
        Scanner sc = new Scanner(str);       // LINE A
        
        // Check if sc has another token in the string
        while(sc.hasNext())
            System.out.println(sc.next());
        
        // Close the scanner
        sc.close();    
    }
}
OUTPUT

Germany
are
the
champions

DESCRIPTION

Here, we have instantiated a Scanner object using a string (LINE A). Then, hasNext() checks to see if scanner has another token in the string. If there is a token, it is displayed.

THINGS TO TRY
  • Create a file named data.txt and store some integers in it (e.g., 1 to 10). Then instantiate a Scanner object by passing this file as a parameter. Try to Use hasNextInt() method and find the sum of all integers stored in the file.

© meritcampus 2019

All Rights Reserved.

Open In App