Text I/O and Exceptions

11.1 - 11.3

Input and Output

File object

Text Output

Use PrintWriter to write text files

Writing text files

Text Input

Use Scanner to read text files

Reading text files

Use the same methods you used for keyborad input You should also close the Scanner when done
in.close();

Mixing next and nextLine

Class Question #1

Suppose the input contains the characters 2nd place. What is the value of number and word after these statements?

int number = in.nextInt(); 
String word = in.next();
  1. number is 2 and word is "nd"
  2. number is 2 and word is "nd place"
  3. number is 2, then an exception is thrown
  4. an exception is thrown because a "n" is not a valid part of an integer

FileNotFoundException

Tricks and techniques for text input:
    hasNext...

Tricks and techniques for text input:
     words

Tricks and techniques for text input:
     processing lines

When the file is line oriented but contains mixed data:

China 1330044605
United States 303824646
...

Tricks and techniques for text input:
     processing lines

When the numeric data contain non-numeric characters like $

China $13344605 N/A
United States $303824646 $46,000
...

Class question #2

An input file contains lines such as

Fred 40
Wilma 28
Mary Ann 30

Consider this code  to process a line:

String line = in.nextLine();
int n = line.lastIndexOf(' ');
String name = line.substring(0, n);
int age = Integer.parseInt(line.substring(n));

What is the problem with this code?

  1. The name includes the trailing space
  2. The call to Integer.parseInt throws an exception
  3. There is no probelm. The code works correctly
  4. The code can not handle a two name with two words

What is the solution?

Throwing an Exception

Command line arguments

Special Topic 11.3 on the web

Arguments array