Java Reference
In-Depth Information
This version of the program works well for almost all cases, but by including the
fencepost solution, which echoes the first word before the loop begins, you've intro-
duced an assumption that there is a first word. If the String has no words at all, this
call on next will throw an exception. So, you need a test for the case in which the
String doesn't contain any words. If you also want this program to produce a com-
plete line of output, you'll have to include a call on println to complete the line of
output after printing the individual words. Incorporating these changes, you get the
following code:
public static void echoFixed(String text, PrintStream output) {
Scanner data = new Scanner(text);
if (data.hasNext()) {
output.print(data.next());
while (data.hasNext()) {
output.print(" " + data.next());
}
}
output.println();
}
Notice that you're now calling output.print and output.println instead of
calling System.out.print and System.out.println . An interesting aspect of this
method is that it can be used not only to send output to an output file, but also to send
it to System.out . The method header indicates that it works on any PrintStream ,
so you can call it to send output either to a PrintStream object tied to a file or to
System.out .
The following complete program uses this method to fix the spacing in an entire
input file of text. To underscore the flexibility of the method, the program sends its
output both to a file ( words2.txt ) and to the console:
1 // This program removes excess spaces in an input file.
2
3 import java.io.*;
4 import java.util.*;
5
6 public class FixSpacing {
7
public static void main(String[] args)
8
throws FileNotFoundException {
9
Scanner input = new Scanner( new File("words.txt"));
10
PrintStream output =
11
new PrintStream( new File("words2.txt"));
12
while (input.hasNextLine()) {
13
String text = input.nextLine();
14
echoFixed(text, output);
Search WWH ::




Custom Search