Download Some notes about using the Scanner class

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Additional notes on the use of the Scanner class
1. Breaking a string into tokens via scanner.
If you need to break a given string (let’s call it str) into tokens, you can use a
scanner: you can create a Scanner object by invoking its constructor with str as a
parameter and then use Scanner class’ methods (hasNext, next, hasNextInt, nextInt,
hasNextFloat, nextFloat, etc.) to check for and to extract tokens.
Example 1: Given a string str that contains a sequence of words separated by
spaces. Output all words in str putting each word on a separate line.
import java.util.*;
public void printWords(String str)
{
Scanner words = new Scanner (str);
while ( words.hasNext() )
System.out.println ( words.next() );
}
Example 2: Input one line which is expected to contain the first, middle and last
names of a person in the given order (and nothing more) and output these three
names in the following format: last name followed by a comma, then the first and
middle names preceded by spaces. If there is no line to input or if the inputted line
doesn’t have the required number of names (there are less or more tokens), output
an appropriate error message for each situation.
Here is the code for this task (assume java.util.Scanner is imported):
Scanner input = new Scanner ( System.in );
String first, middle, last;
try {
Scanner line = new Scanner ( input.nextLine() );
//nextLine will throw a NoSuchElementException if there is no line to input (Ctrl+D is pressed)
try {
first = line.next();
middle = line.next();
last = line.next();
//next will throw a NoSuchElementException if there is no token to read
if (line.hasNext())
System.out.println (“Invalid line: more than three tokens.”);
else
System.out.println (last + “, “ + first + “ “ + middle);
}
catch (NoSuchElementException e)
{
System.out.println (“Invalid line: less than three tokens.”); }
}
catch (NoSuchElementException e)
{
System.out.println (“Error: no line to input.”); }
2. Inputting from a file via scanner
If you need to input data from a text file, you can define a Scanner object which
streams the input from the given file (instead of System.in) and then use Scanner
class’ methods (hasNextLine, nextLine, hasNext, next, hasNextInt, nextInt,
hasNextFloat, nextFloat, etc.) to get the data exactly the same way you would
work with the standard input.
Here are few important things to remember:
a) You need to import java.io library in addition to the java.util:
import java.util.* ;
import java.io.* ;
b) Inputting from a file may generate IOException type exceptions. These are
unchecked exceptions, so if you are not planning to handle them, you need to
make sure to include a throws clause in your method’s header:
public void myMethod(…) throws IOException
{
: //code contains file input where IOException type exceptions are not handled
}
c) declare the scanner as follows:
Scanner fileIn = new Scanner ( new FileReader ( “myFile.dat” ) );
or
Scanner fileIn = new Scanner ( new FileReader ( filename ) );
where myFile.dat is the name of the input file, filename is a variable
containing the name of the input file.
Example: Output the content of the input file data.txt on the screen keeping all the
original line breaking.
import java.util.* ;
import java.io.* ;
public static void main(String[] aregs) throws IOException
{
Scanner input = new Scanner ( new FileReader ( “data.txt” ) );
while ( input.hasNextLine() )
System.out.println ( input.nextLine() );
}