Prev | Current Page 234 | Next

Carl Reynolds and Paul Tymann

"Schaum's Outline of Principles of Computer Science"

..
Scanner scanner = new Scanner(System.in);
// Obtain input
System.out.print("Enter balance: ");
double balance = scanner.nextDouble();
...
The Scanner class has many methods, and you should consult the Java API documentation to see what
they are, and what choices you have.
You can also use a Scanner to read from a file. To associate a Scanner with a file of text, just pass
a FileReader object to the Scanner constructor:
sc = new Scanner(new FileReader( myFile.txt ) );
To read lines of text, you can use the nextLine() method of Scanner to transfer a line of text
into a String variable. You can also use the hasNextLine() method to test to see whether there is
something to read. Here??™s a snippet of code to loop, reading text for processing into a String called
lineOfData.
CHAP. 5] PROGRAMMING IN JAVA 91
String lineOfData;
Scanner sc = new Scanner( myFile.txt );
while( sc.hasNextLine() ) {
lineOfData = sc.nextLine();
...
}//while
When the program reaches the EOF, the hasNextLine() method will return false, and the program will
exit the while loop.
PRINTWRITER
The PrintWriter is another very convenient I/O class; it makes writing text to a file as easy as writing
text to the display. To create a PrintWriter that is associated with a file, you simply pass the name of the
file to the constructor.


Pages:
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
Apartamenty Świnoujście noclegi hel Lokaty jednodniowe projekty domków letniskowych męskie skarpetki rowerowe