Java Reference
In-Depth Information
Self-Test Exercises
18. What would the program in Display 2.12 output if there is no fi le named
player.txt
in the same directory as the Java program?
19. What is missing from the following code, which attempts to open a fi le and
read an integer?
import
java.util.Scanner;
import
java.io.FileInputStream;
import
java.io.FileNotFoundException;
public class
ReadInteger
{
public static void
main(String[] args)
{
Scanner fileIn =
new
Scanner(
new
FileInputStream("datafile.txt"));
int
num = fileIn.nextInt();
System.out.println(num);
}
}
Chapter Summary
•
You can use
System.out.println
for simple console output.
•
You can use
System.out.printf
for formatted console output.
•
You can use
NumberFormat.getCurrencyInstance()
to produce an object that can
convert numbers to strings that show the number as a correctly formatted currency
amount, for example, by adding a dollar sign and having exactly two digits after the
decimal point.
•
You can use the class
DecimalFormat
to output numbers using almost any format
you desire.
•
You can use an object of the class
Scanner
for reading keyboard input.
•
You can use an object of the class
Scanner
for reading input from a text file.
Answers to Self-Test Exercises
1 .
HelloJoe
2 .
System.out.println("One two buckle your shoe.");
System.out.println("Three four shut the door.");
3 .
System.out.println
ends a line of input, so the next output goes on the next
line. With
System.out.print
, the next output goes on the same line.