Problem 0: Review old labs, quizzes, and homeworks.
Problem 1: Suppose you have to implement a class called Image that can be used to create objects that represent two-dimensional grayscale images. Each object will have a 2-D array of ints that records how much gray is in each pixel of the image (0 means black; 255 means white). The skeleton of the class definition is below.
public class Image {
// Constructs a new image with the given dimensions and initializes it
// to all white.
public Image(int w, int h)
{
width = w; height = h; grayMap = new int[h][w]; for (int row = 0; row < h; row++) for (int col = 0; col < w; col++) grayMap[row][col] = 255;
}
// Sets the pixel at the given coordinates to the given value.
public void setPixel(int x, int y, int grayValue)
{
grayMap[y][x] = grayValue;
}
// Sets the pixels in the given row to the values in the given string.
// The values in the string should be separated by spaces
// (e.g. "100 125 ...").
public void setRow(int y, String values)
{
StringTokenizer tok = new StringTokenizer(values); for (int col = 0; col < width; col++) grayMap[y][col] = Integer.parseInt(tok.nextToken());
}
// Reads an image from a file.
public void readImage(String filename) { ... }
protected int[][] grayMap;
protected int width, height;
}
Problem 2: Suppose you have a complete implementation of the Image class. Write the complete class definition for a new class called Icon that has the same functionality as Image except:
Icon ico = new Icon("flag.pgm");
ico.setPixel(0, 0, 128); // set upper left to middle gray
public class Icon extends Image
{
public Icon(String fname)
{
super(8, 8);
readImage(fname);
}
}
Problem 3: Write a method called grep that takes three arguments: the name an input file, the name of an output file, and a string to search for within the input file. The method should open the input file, create the output file, and copy to the output file every line from the input file that contains the search string. For example, if the input file contains
Joanna: So where do you work, uh, Peter? Peter: Initech Joanna: And, uh, what do you do there?and the search string was Peter then the output file should contain
Joanna: So where do you work, uh, Peter? Peter: Initech
public static void grep(String inname, String outname, String search) throws IOException
{
BufferedReader in = new BufferedReader(new FileReader(inname));
PrintWriter out = new PrintWriter(new FileWriter(outname));
String line;
while ((line = in.readLine()) != null)
if (line.indexOf(search) != -1)
out.println(line);
out.close();
}
Problem 4: Write a method that takes as its parameter the name of a file containing start and stop times in the form "hh:mm hh:mm" and adds up and returns the total time intervals in minutes. For example, if the input file is
3:15 4:00 10:30 10:40then the method would return 55. You may assume that there is a method computeInterval(int startHr, int startMin, int endHr, int endmin) that computes the number of minutes between two times and that the times will not wrap around days.
public int readTimes(String fname) throws IOException
{
BufferedReader in = new BufferedReader(new FileReader(fname));
int total = 0;
String line;
while ((line = in.readLine()) != null)
{
StringTokenizer tok = new StringTokenizer(line, ": ");
int h1 = Integer.parseInt(tok.nextToken());
int m1 = Integer.parseInt(tok.nextToken());
int h2 = Integer.parseInt(tok.nextToken());
int m2 = Integer.parseInt(tok.nextToken());
total += computeInterval(h1, m1, h2, m2);
}
return total;
}
Problem 5: Redo problem 2, but do the computation in seconds. Assume that you have an appropriate version of the computeInterval method, and that each time in the file may or may not contain the seconds (assume 0 if the seconds are omitted). For example, the input file may contain
3:15 3:17:20 4:00:01 4:00:10in which case the new method should return 149.
public int readTimes(String fname) throws IOException
{
BufferedReader in = new BufferedReader(new FileReader(fname));
int total = 0;
String line;
while ((line = in.readLine()) != null)
{
StringTokenizer tok = new StringTokenizer(line);
String start = tok.nextToken();
String end = tok.nextToken();
tok = new StringTokenizer(start, ":");
int h1 = Integer.parseInt(tok.nextToken());
int m1 = Integer.parseInt(tok.nextToken());
int s1 = 0;
if (tok.hasMoreTokens())
s1 = Integer.parseInt(tok.nextToken());
tok = new StringTokenizer(end, ":");
int h2 = Integer.parseInt(tok.nextToken());
int m2 = Integer.parseInt(tok.nextToken());
int s2 = 0;
if (tok.hasMoreTokens())
s2 = Integer.parseInt(tok.nextToken());
total += computeInterval(h1, m1, s1, h2, m2, s2);
}
return total;
}
Problem 6:
Write a method called blankCount that, given the name of
a file as an argument, returns the number of blank lines in the file.
If the file does not exist, blankCount should return 0.
If any other error occurs when reading from the file the method should
use System.println to display an error message and then
call System.exit(0) to terminate the program.
blankCount must not throw any exceptions back to the caller.
public int blankCount(String fname)
{
try {
BufferedReader in = new BufferedReader(new FileReader(fname));
int count = 0;
String line;
while ((line = in.readLine()) != null)
if (line.length() == 0)
count++;
return count;
}
catch (FileNotFoundException e)
{
}
catch (IOException e)
{
System.err.println("Error reading file " + fname);
System.exit(0);
}
return 0;
}
Problem 7: Rewrite the following classes so they are both subclasses of a class called Dwelling. Write the code for Dwelling as well. Try to avoid repeating code as much as possible. Write the classes so that any common methods can be called through a Dwelling reference.
public class Dwelling
{
protected int size;
protected String address;
public Dwelling(int sz, String addr)
{
size = sz;
address = addr;
}
public double estimateUtilities() {
return size * size / Math.exp(size / 3.0);
}
public String getAddress() {
return address;
}
public int getSize() {
return size;
}
}
public class House extends Dwelling {
private int size, taxes;
private String address;
public House(int sz, String addr, int t) {
super(sz, addr);
size = sz;
address = addr;
taxes = t;
}
public int getTaxes() {
return taxes;
}
public double estimateUtilities() {
return size * size / Math.exp(size / 3.0);
}
public String getAddress() {
return address;
}
}
public class Apartment {
private int size;
private String address;
public Apartment(int sz, String addr) {
super(sz, addr);
size = sz;
address = addr;
}
public double estimateUtilities() {
return size * size / Math.exp(size / 3.0) super.estimateUtilities() - size getSize()/ 10;
}
public String getAddress() {
return address;
}
}
Problem 8: Create an application with the following interface.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class X2P_Q1 extends JApplet
{
private JTextField addrInput;
private JCheckBox[] options;
private static final String[] optionNames = {
"Dishwasher", "Washer/Dryer", "Refrigerator", "Fireplace",
"Garage", "Pool"
};
public void init()
{
Container c = getContentPane();
addrInput = new JTextField();
JPanel addrPanel = new JPanel(new BorderLayout());
addrPanel.add(new JLabel("Address"), BorderLayout.WEST);
addrPanel.add(addrInput, BorderLayout.CENTER);
JPanel optionPanel = new JPanel(new GridLayout(2, 3));
options = new JCheckBox[optionNames.length];
for (int i = 0; i < optionNames.length; i++)
{
options[i] = new JCheckBox(optionNames[i]);
optionPanel.add(options[i]);
}
JButton createButton = new JButton("Create");
createButton.addActionListener(new CreateListener());
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(new ClearListener());
JButton quitButton = new JButton("Quit");
quitButton.addActionListener(new QuitListener());
JPanel buttonPanel = new JPanel(new GridLayout(1, 3, 5, 5));
buttonPanel.add(createButton);
buttonPanel.add(clearButton);
buttonPanel.add(quitButton);
c.setLayout(new BorderLayout());
c.add(addrPanel, BorderLayout.NORTH);
c.add(optionPanel, BorderLayout.CENTER);
c.add(buttonPanel, BorderLayout.SOUTH);
}
private class CreateListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Created " + addrInput.getText());
for (int i = 0; i < options.length; i++)
if (options[i].isSelected())
System.out.println(optionNames[i]);
}
}
private class ClearListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
addrInput.setText("");
for (int i = 0; i < options.length; i++)
options[i].setSelected(false);
}
}
private class QuitListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(1);
}
}
}
Problem 9: Consider the following method
public static int bar(String s)
{
if (s.length() < 2)
return 0;
else if (s.charAt(0) != s.charAt(1))
return 1 + bar(s.substring(1));
else
return bar(s.substring(1));
}
Problem 10:
Write a recursive method that computes ak, where
ak is defined as follows:
a0 = 2,
a1 = 1, and
ak = ak-1 + 2 * ak-2
for k > 1.
public static int a(int k)
{
if (k < 0)
throw new IllegalArgumentException();
else if (k == 0)
return 2;
else if (k == 1)
return 1;
else
return a(k - 1) + 2 * a(k - 2);
}
Problem 11: Consider the following recursive function.
public int w(int k)
{
if (k == 0)
return 2;
else if (k <= 3)
return 1;
else if (w(k - 1) + w(k - 2) + w(k - 3) % 3 == 0)
return 2;
else
return 1;
}
Draw the recursion tree for the call w(5). What value does
w(5) return? What value does w(7) return?
w(5)
/ | \
w(4) w(3) w(2)
/ | \
w(3) w(2) w(1)
w(5) and w(7) both return 1.