

PrintWriter for output, Scanner for
inputFile parameter
new PrintWriter(new File("output.txt"))new Scanner(new File("input.txt"),
"UTF-8")throws FileNotFoundException
to methodin.nextInt()/in.nextDouble()in.nextLine()in.next()in.useDelimiter(""), then
in.next())1729 Harry 1730 Wilma
int studentID = in.nextInt();

Harry
reads an empty string! int studentID = in.nextInt();
in.nextLine(); // Consume the \n
String name = in.nextLine();
Suppose the input contains the characters 6,995.00 12. What is the value of price and quantity after these statements?
double price = in.nextDouble(); int quantity = in.nextInt();
String methods trim, indexOf,
lastIndexOfCharacter predicates isDigit,
isWhitespaceString line = in.nextLine(); // Reads line such as United States 303824646 Scanner lineIn = new Scanner(line); String country = lineIn.next(); while (!in.hasNextDouble()) country = country + " " + lineIn.next(); double area = lineIn.nextDouble();
Integer.parseInt/Double.parseDouble
(but remember to trim!)in.useDelimiter("[^A-Za-z]+") 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?
Integer.parseInt throws an exceptionpublic class BankAccount
{
public void withdraw(double amount)
{
if (amount > balance)
{
throw new IllegalArgumentException("Amount exceeds balance");;
}
balance = balance - amount;
}
. . .
}
public static Comparable smallest(Comparable[] values)
{
if (values.length == 0) throw new XXXException(); // What should we throw?
Comparable smallestSoFar = values[0];
for (int i = 1; i < values.length; i++)
if (values[i].compareTo(smallestSoFar) < 0)
smallestSoFar = values[i];
return smallestSoFar;
}
ArrayIndexOutOfBoundsExceptionIllegalArgumentExceptionIllegalStateExceptionNoSuchElementException