CS 46B - Lecture 5

Cover page image

Cay S. Horstmann

Pre-class reading

Homework 3

Text I/O

Classifiying Characters

Scanning Strings

Converting to Numbers

Lecture 5 Clicker Question 1

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. Double names (such as “Mary Ann”) are not stored in name
  4. The code won't work with characters such as 😻 that require two char values

Split

Lecture 5 Clicker Question 2

Complete this program to find the sum of the numbers in the second to last column. Use split.

The input file looks like this:

Abraham Lincoln		6 ft 4 in	193 cm
Lyndon B. Johnson	6 ft 3 1⁄2 in	192 cm
Thomas Jefferson	6 ft 2 1⁄2 in	189 cm
...

What result do you get?

  1. 179.81
  2. 7732
  3. 7842
  4. Something else

Caution: Mixing next and nextLine

Lecture 5 Clicker Question 3

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

Useful Format Specifiers

Lecture 5 Clicker Question 4

Have another look at the example with the clams. Why can't you use the simpler form

out.printf("%-10s:%10.2f", items[i], prices[i]);
  1. A colon is not a valid flag
  2. The colon would be at the wrong place
  3. You can't format items[i] as a string with %s
  4. You can't have a negative width of -10

Command-Line Arguments

Before Next Class