CS 46B - Lecture 5

Cover page image

Cay S. Horstmann

Pre-class reading

Text I/O

Mixing next and nextLine

Lecture 5 Clicker Question 1

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();
  1. price is 6995 and quantity is 12
  2. price is "6,995.00" and quantity is 12
  3. price is 6, then an exception is thrown because the comma is not a valid part of an integer
  4. an exception is thrown because a comma is not a valid part of a floating-point number

Text Input Tricks

Lecture 5 Clicker 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?

Throwing Exceptions

Hierarchy of Exception Classes

Lecture 5 Clicker Question 3

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;
}   
  1. ArrayIndexOutOfBoundsException
  2. IllegalArgumentException
  3. IllegalStateException
  4. NoSuchElementException

Lab

???