Java Reference
In-Depth Information
4. Console console = System.console();
5. if(console == null) {
6. throw new IOException(“Console not available”);
7. }
8. String formula = “Formula = “;
9. double radius = 2.0;
10. console.format(“%10s%12.10f * %3$4.2f * %3$4.2f%n”,
11. formula, Math.PI, radius);
12. double area = Math.PI * radius * radius;
13. console.format(“%10s%16.13f%n”, “Result = “, area);
Line 4 obtains a reference to the Console object, and line 5 makes sure that it worked
by checking for a null return value. Line 10 formats four conversions, but notice there
are only three arguments. The third argument, radius , is formatted twice (demonstrating
that arguments can be reused in the format specifi er). Also the two strings formula and
”Result = “ have the same width so that they line up nicely. The output of the code is sent
to the console and looks like this:
Formula = 3.1415926536 * 2.00 * 2.00
Result = 12.5663706143592
You can also use the Console object to read keyboard input from the user. The Console
class defi nes four methods for reading in a single line of text from the console:
public String readLine() reads in a single line as a String .
public String readLine(String fmt, Object... args) displays a formatted
prompt, then reads a single line as a String .
public char [] readPassword() reads a line of text as a char array with echoing
disabled.
public char [] readPassword(String fmt, Object... args) displays a formatted
prompt and then reads a line of text as a char array with echoing disabled.
The readPassword methods provide support for secure password entry by disabling the
input and also by storing the input in an array of char s, allowing you to overwrite the pass-
word in memory after it has been used without waiting for the garbage collector.
The following code demonstrates reading input using the Console object by prompting the
user for a username and password. Study the code and see if you can determine its output:
10. Console console = System.console();
11. if(console == null) {
12. throw new IOException(“Console not available”);
13. }
14. String userprompt = “Enter username:”;
15. String passprompt = “Password:”;
Search WWH ::




Custom Search