Page 671 - Introduction to Programming with Java: A Problem Solving Approach
P. 671
3. [after §15.3] Provide the missing code fragments in the following Java program so that it successfully writes the indicated churchill string to a file called elAlamein.txt. Create fileOut so that the new data overwrites any previous data in an existing file having the specified name.
/*************************************************************
*
TextWriter.java
Dean & Dean
This writes two lines of text to a text file.
*************************************************************/
*
*
*
<fragment>
public class TextWriter
{
}
// end TextWriter class
public static void main(String[] args)
{
}
// end main
String[] churchill =
{"Before Alamein we never had a victory.",
"After Alamein we never had a defeat."};
PrintWriter fileOut;
try
{
}
{
}
<fragment>
for (String line : churchill) {
<fragment> <fragment>
}
Apago PDF Enhancer
catch (FileNotFoundException e)
System.out.println(e.getMessage());
4. [after §15.3] Modify the code in the previous exercise so that it appends to the text already in the elAlamein.txt file the year in which the battle took place, 1942. In the program, create this additional piece of information as an integer, like this:
int year = 1942;
In the file, put this additional piece of information on the next line, after the previous text.
5. [after§15.4]Theprogrambelowissupposedtoopenafilewhosefullpathnameisprovidedbytheuserina keyboard entry. Then it is supposed to count the number of words in the file, where any kind of whitespace is a word delimiter. The program is complete except for a code fragment of several lines in the try block. Provide the missing code fragment. Use an anonymous File object as the Scanner argument when you instantiate the fileIn object. Of course, you can use the same Scanner-class hasNext and next
Exercises 637