|
Core Java 2 Volume I - Fundamentals Authors: Horstmann C. S., Cornell G. Published year: 2003 Pages: 31/132 |
Input and OutputTo make our example programs more interesting, we want to accept input and properly format the program output. Of course, modern programs use a GUI for collecting user input. However, programming such an interface requires more tools and techniques than we have at our disposal at this time. Because the first order of business is to become more familiar with the Java programming language, we make do with the humble console for input and output for now. GUI programming is covered in Chapters 7 through 9. Reading InputYou saw that it is easy to print output to the "standard output stream" (that is, the console window) just by calling System.out.println . Oddly enough, before JDK 5.0, there was no convenient way to read input from the console window. Fortunately, that situation has finally been rectified. To read console input, you first construct a Scanner that is attached to the "standard input stream" System.in . Scanner in = new Scanner(System.in); Now you use the various methods of the Scanner class to read input. For example, the nextLine method reads a line of input.
System.out.print("What is your name? ");
String name = in.nextLine();
Here, we use the nextLine method because the input might contain spaces. To read a single word (delimited by whitespace), call String firstName = in.next(); To read an integer, use the nextInt method.
System.out.print("How old are you? ");
int age = in.nextInt();
Similarly, the nextdouble method reads the next floating-point number. The program in Example 3-2 asks for the user's name and age and then prints a message like Hello, Cay. Next year, you'll be 46 Finally, add the line import java.util.*; at the beginning of the program. The Scanner class is defined in the java.util package. Whenever you use a class that is not defined in the basic java.lang package, you need to use an import directive. We look at packages and import directives in more detail in Chapter 4. Example 3-2. InputTest.java
1. import java.util.*;
2.
3. public class InputTest
4. {
5. public static void main(String[] args)
6. {
7. Scanner in = new Scanner(System.in);
8.
9. // get first input
10. System.out.print("What is your name? ");
11. String name = in.nextLine();
12.
13. // get second input
14. System.out.print("How old are you? ");
15. int age = in.nextInt();
16.
17. // display output on console
18. System.out.println("Hello, " + name + ". Next year, you'll be " + (age + 1));
19. }
20. }
NOTE
java.util.Scanner 5.0
javax.swing.JOptionPane 1.2
java.lang.System 1.0
Formatting OutputYou can print a number x to the console with the statement System.out.print(x) . That command will print x with the maximum number of non-zero digits for that type. For example, double x = 10000.0 / 3.0; System.out.print(x); prints 3333.3333333333335 That is a problem if you want to display, for example, dollars and cents . Before JDK 5.0, formatting numbers was a bit of a hassle. Fortunately, JDK 5.0 brought back the venerable printf method from the C library. For example, the call
System.out.printf("%8.2f", x);
prints x with a field width of 8 characters and a precision of 2 characters. That is, the printout contains a leading space and the seven characters 3333.33 You can supply multiple parameters to printf , for example:
System.out.printf("Hello, %s. Next year, you'll be %d", name, age);
Each of the format specifiers that start with a % character is replaced with the corresponding argument. The conversion character that ends a format specifier indicates the type of the value to be formatted: f is a floating-point number, s a string, and d a decimal integer. Table 3-5 shows all conversion characters. Table 3-5. Conversions for printf
Table 3-7. Date and Time Conversion Characters
In addition, you can specify flags that control the appearance of the formatted output. Table 3-6 shows all flags. For example, the comma flag adds group separators. That is,
System.out.printf("%,.2f", 10000.0 / 3.0);
Table 3-6. Flags for printf
prints 3,333.33 You can use multiple flags, for example, "%,(.2f" , to use group separators and enclose negative numbers in parentheses.
NOTE
You can use the static String.format method to create a formatted string without printing it:
String message = String.format("Hello, %s. Next year, you'll be %d", name, age);
Although we do not describe the Date type in detail until Chapter 4, we do, in the interest of completeness, briefly discuss the date and time formatting options of the printf method. You use two a two-letter format, starting with t and ending in one of the letters of Table 3-7. For example,
System.out.printf("%tc", new Date());
prints the current date and time in the format Mon Feb 09 18:05:19 PST 2004 As you can see in Table 3-7, some of the formats yield only a part of a given date, for example, just the day or just the month. It would be a bit silly if you had to supply the date multiple times to format each part. For that reason, a format string can indicate the index of the argument to be formatted. The index must immediately follow the % , and it must be terminated by a $ . For example,
System.out.printf("%1$s %2$tB %2$te, %2$tY", "Due date:", new Date());
prints Due date: February 9, 2004 Alternatively, you can use the < flag. It indicates that the same argument as in the preceding format specification should be used again. That is, the statement
System.out.printf("%s %tB %<te, %<tY", "Due date:", new Date());
yields the same output as the preceding statement.
CAUTION
You have now seen all features of the printf method. Figure 3-7 shows a syntax diagram for format specifiers. Figure 3-7. Format specifier syntax
NOTE
TIP
|
|
|
|
Core Java 2 Volume I - Fundamentals Authors: Horstmann C. S., Cornell G. Published year: 2003 Pages: 31/132 |
![]() Thinking in Java (4th Edition) | ![]() Core Java, Volume I--Fundamentals (8th Edition) | ![]() Core Java, Vol. 2: Advanced Features, 8th Edition | ![]() Effective Java: Programming Language Guide (Java Series) | ![]() Head First Java |
![]() Thinking in Java (4th Edition) | ![]() Core Java, Volume I--Fundamentals (8th Edition) |
![]() Core Java, Vol. 2: Advanced Features, 8th Edition | ![]() Effective Java: Programming Language Guide (Java Series) |
![]() Head First Java |