Constructors
Scanner class has several constructors. Among them, the following are particularly useful.
Let's now see different ways of instantiating a
Scanner
object.
Instantiating a Scanner object by passing a File object as parameter import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
class ScannerConstructorDemo1
{
public static void main(String arg[])
{
// Read from a file rather than the keyboard
Scanner sc = new Scanner(new File("FIFA14.txt")); // LINE A
// Check if sc has another token in the file
while(sc.hasNext())
System.out.println(sc.next());
// Close the scanner
sc.close();
}
}
OUTPUTGermany
Argentina
Netherlands
Brazil
Colombia
France
Costa-Rica
Belgium
DESCRIPTIONHere, we have instantiated a Scanner
object by passing a file (FIFA14.txt
)(LINE A
). (Assume that FIFA14.txt exists.) hasNext()
returns true if the input file has another token. SOP statement prints out each token. Finally, close()
closes the scanner.
- To read from keyboard rather than from a file, we instantiate a Scanner object with
System.in
.
NOTE:
System.in
is an
InputStream
.
Scanner in = new Scanner(System.in); // Reading from the keyboard
Let's now instantiate a
Scanner
object by passing a String as parameter.
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();
}
}
OUTPUTGermany
are
the
champions
DESCRIPTIONHere, 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.