PIC20A Final Exam
Instructions
- The exam consists of 19 pages(including this page). You are responsible
for checking the number of pages
-
Please read and answer all the questions carefully.
The point value for each question in indicated. The total number of points available is 150.
If you have trouble with a question, leave it and try another.
- Unless otherwise stated, you may assume when code is given that the code compiles and
is correct. When you are asked to write code, you are expected to write code in good style and
with proper indentation.
- Good luck!
| Last Name:_________________ |
First Name:________________ |
| Student ID:_________________ |
|
| Question |
Q1 | Q2 | Q3 |
Q4 | Q5 |
Q6 |
Total(150pts) |
| Score |
|
|
|
|
|
|
|
Q1)(32pts)
(a)
Write down the output of java CaseTest:
public class CaseTest {
public void test(int x) {
switch(x) {
case 1:
System.out.print("One ");
case 2:
System.out.print("Two ");
break;
case 3:
System.out.print("Three ");
default:
System.out.print("Do What?");
}
}
public static void main(String[] args) {
CaseTest a = new CaseTest();
System.out.println("Ouput 0");
a.test(0);
System.out.println();
System.out.println("Output 1");
a.test(1);
System.out.println();
System.out.println("Output 2");
a.test(2);
System.out.println();
System.out.println("Output 3");
a.test(3);
System.out.println();
System.out.println("Output 4");
a.test(4);
}
}
Answer:
(b)
1. public int test(String x, int n) {
2. if(n == 0) return n;
3. else if(n == 1) {
4. if(x != null) return 5;
5. }
6. else if( n == 2 && x != null) {
7. if(x.equals("YES") ) return 3;
8. else if( x.equals("NO")) return 4;
9. }
10. return -1;
11. }
Which of the following statements are ture? (circle all the correct answers)
- if the input
n = 1, line 6 will always be executed.
- if the input string
x is "NO" and n is 2, the method returns 4.
- If the input
n is 1 and the input string is "YES", the method returns 3.
- The
else on line 6 goes with the if on line 3
(c)
Assume this class hierarchy:
Animal
|
Mammal
|
--------------------------------------------
| | | |
Dog Cat Raccoon SwampThing
(implements (implements
Washer) Washer)
Consider the following code:
1. Raccoon rocky;
2. SwampThing pogo;
3. Washer w;
4.
5. rocky = new Raccoon();
6. w = rocky;
7. pogo = w;
Which of the following statements are true? (Circle the correct answer(s))
A) Line 6 will not compile; an explicit cast is required to convert a Raccoon to a Washer.
B) Line 7 will not compile; an explicit cast is required to convert a Washer to a SwampThing.
C) The code will compile and run.
D) The code will compile but will throw an exception at line 7,
because runtime conversion from an interface to a class is not permitted.
E) The code will compile but will throw an exception at line 7,
because the runtime class of w cannot be converted to type SwampThing.
(d)
Given the following code what will be the output of java ObParm?
class ValHold{
public int i = 10;
}
public class ObParm{
public static void main(String argv[]){
ObParm o = new ObParm();
o.amethod();
}
public void amethod(){
int i = 99;
ValHold v = new ValHold();
v.i=30;
another(v,i);
System.out.print( v.i );
}//End of amethod
public void another(ValHold v, int i){
i=0;
v.i = 20;
ValHold vh = new ValHold();
v = vh;
System.out.print(v.i);
System.out.print(i);
}//End of another
}
Answer:
(e)
Given the following class definition, which of the following methods could be legally placed after the comment(circle the correct answer(s))
public class Rid{
public void amethod(int i, String s){}
//Here
}
- public void amethod(String s, int i){}
- public int amethod(int i, String s){}
- public void amethod(int i, String mystring){}
- public void Amethod(int i, String s) {}
(f)
Circle the correct answer:
You execute the code below in an empty directory. What is the result? Circle the current answer(s).
1. File f1 = new File("dirname");
2. File f2 = new File(f1, "filename");
A) A new directory called dirname is created in the current working directory.
B) A new directory called dirname is created in the current working directory. A new file called filename is created in directory dirname.
C) A new directory called dirname and a new file called filename are created, both in the current working directory.
D) A new file called filename is created in the current working directory.
E) No directory is created, and no file is created.
(g)
What is the output of the following program?
public class Ex {
public static int average(String[] s, int n) {
int sum=0;
int index=0;
try {
System.out.println("For loop");
for(int i = 0; i < n; i++) {
index = i;
sum+=Integer.parseInt(s[i]);
}
System.out.println("End For Loop");
return sum/n;
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("Error A " +index);
} catch(NullPointerException ex) {
System.out.println("Error B " + index);
} catch (NumberFormatException nfe) {
System.out.println("Error C " + index );
} catch (ArithmeticException ex) {
System.out.println("Error D " + index);
}
return -1;
}
public static void main(String[] args) {
String[] a=null;
int x;
System.out.println("output 1");
x = average(a, 3);
System.out.println(x);
a = new String[3];
a[0] = "1";
a[1] = "3";
a[2] = "5";
System.out.println();
System.out.println("output 2");
x = average(a,2);
System.out.println(x);
System.out.println();
System.out.println("output 3");
x = average(a, 0);
System.out.println(x);
System.out.println();
System.out.println("output 4");
x = average(a, 4);
System.out.println(x);
a[2] = "Hi";
System.out.println();
System.out.println("output 5");
x = average(a, 5);
System.out.println(x);
}
}
Answer
(h)
Draw (sketch) the output of java LayoutTest. Notice that the width of the JFrame is not big enough to hold all the buttons
on one single line.
import java.awt.*;
import javax.swing.*;
public class LayoutTest {
public static void main(String[] args) {
String[] s = {"America", "British", "Canada", "Denmark", "Egypt"};
JButton[] button = new JButton[5];
JFrame f = new JFrame("Countries");
f.getContentPane().setLayout(new FlowLayout(FlowLayout.RIGHT));
for(int i = 0; i < 5; i++) {
button[i] = new JButton(s[i]);
f.getContentPane().add(button[i]);
}
f.getContentPane().add(new JButton("ABC"), 3);
f.getContentPane().remove(4);
f.setSize(230,100);
f.setVisible(true);
}
}
Answer
(i)
Sketch the output of the java GraphTest
import java.awt.*;
import javax.swing.*;
public class GraphTest extends JFrame {
public void paint(Graphics g) {
g.setColor(Color.red);
g.drawRect(50,50,100,100);
g.fillOval(50,50,100,100);
g.setColor(Color.black);
g.fillOval(100,100, 75, 75);
g.drawLine(50,50,100,100);
g.drawString("exam", 50,150);
}
public static void main(String[] args) {
GraphTest f = new GraphTest();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(200,200);
f.setVisible(true);
}
}
Answer:
Q2) (20 pts)
Find out the compiling errors of the following programs. Circle the errors and fix them. Write your corrections
next to the errors you circle. There may be more than one errors in each program.
(a)
InterfaceTest.java
public interface InterfaceTest {
int a = 5;
void methodA();
int methodB(int x);
}
ClassA.java
public class ClassA implements InterfaceTest {
public ClassA() {
methodA();
}
public void methodA() {
System.out.println("A");
}
}
(b)
public class ClassB {
int div(int a, int b) {
try {
int result = a/b;
} catch (ArithmeticException ex) {
System.out.println("something is wrong");
return 0;
}
return result;
}
}
(c)
import java.awt.*;
public class ClassC {
public static void main(String[] args) {
Color c = new Color(0.5,0.5,0.5);
Color d = new Color(1,2,3);
Color e = d.red.blue.green;
}
}
(d)
import javax.swing.*;
public class ClassD {
public static void main(String[] args) {
JLabel[] label = new JLabel[5];
JFrame f = new JFrame();
for(int i = 0; i < 5; i++) {
label[i] = new JLabel();
label[i].setText(i);
f.getContentPane().add(label[i]);
}
}
}
(e)
Class Ex has 3 static methods methodA(), methodB(), methodAB().
methodA throws ExceptionA, methodB() throws ExceptionB,
methodAB throws both ExceptionA and ExceptionB.
Here are the class diagrams of ExceptionA and ExceptionB:
java.lang.Object
|
+--java.lang.Throwable
|
+--java.lang.Exception
|
+--java.lang.RuntimeException
|
+--ExceptionA
|
java.lang.Object
|
+--java.lang.Throwable
|
+--java.lang.Exception
|
+--java.io.IOException
|
+--ExceptionB
|
Find errors and fix the following codes.
public class Test {
public void test1() {
Ex.methodA();
}
public void test2() {
Ex.methodB();
}
public void test3() {
Ex.methodAB();
}
public void test4() {
try {
Ex.methodAB();
} catch (ExceptionA ex) {
}
}
public void test5() {
try {
Ex.methodAB();
} catch (ExceptionB ex) {
}
}
}
Q3) (20 pts)
(a)
Rewrite the following program without any import statement.
import java.awt.*;
import javax.swing.*;
public class Rewrite {
public static void main(String[] args) {
JFrame f = new JFrame("Hi");
f.getContentPane().setLayout(new BorderLayout(5,5));
f.getContentPane().add(new JLabel("abc"));
f.setSize(100,100);
f.setVisible(true);
}
}
Answer:
public class Rewrite {
public static void main(String[] args) {
// your codes
f.setSize(100,100);
f.setVisible(true);
}
}
(b)
Write a method int count(File folder).
- It returns the total number of folders and files directly inside
folder. You don't have to count the
files or subfolders inside another subfolder.
- The method returns 0 if
folder doesn't exists
- The codes should be short.
Answer:
int count(File folder) {
// your codes
}
Q4)(28 pts)
Consider the following program
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ActionTest extends JFrame {
JButton buttonA = new JButton("A");
JButton buttonB = new JButton("B");
JButton buttonC = new JButton("C");
JLabel display = new JLabel("0", JLabel.CENTER);
Container contentPane = getContentPane();
public ActionTest() {
contentPane.add(buttonA, BorderLayout.CENTER);
contentPane.add(buttonB, BorderLayout.EAST);
contentPane.add(buttonC, BorderLayout.WEST);
contentPane.add(display, BorderLayout.SOUTH);
buttonA.addActionListener(new Action1(display, 3));
buttonB.addActionListener(new Action1(display, 2));
buttonC.addActionListener(new Action2(display));
}
public static void main(String[] args) {
ActionTest f = new ActionTest();
f.setSize(200,100);
f.setVisible(true);
}
}
class Action1 implements ActionListener {
JLabel label;
int x;
public Action1(JLabel label, int x) {
this.label = label;
this.x = x;
}
public void actionPerformed(ActionEvent e) {
int num = Integer.parseInt(label.getText()) + x;
label.setText("" + num);
}
}
class Action2 implements ActionListener {
JLabel label;
public Action2(JLabel label) {
this.label = label;
}
public void actionPerformed(ActionEvent e) {
label.setText("" + 3);
}
}
a)
Draw (sketch) the output of java ActionTest:
b)
Briefly describe what happens what you (i) click on buttonA (ii) click on buttonB (iii) click on buttonC?
c)
When will be the number on display after you click on buttonC, then click on buttonB,
and then click on buttonA?
d)
Rewrite the above program using anonymous class only.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ActionTest extends JFrame {
JButton buttonA = new JButton("A");
JButton buttonB = new JButton("B");
JButton buttonC = new JButton("C");
JLabel display = new JLabel("0", JLabel.CENTER);
Container contentPane = getContentPane();
public ActionTest() {
contentPane.add(buttonA, BorderLayout.CENTER);
contentPane.add(buttonB, BorderLayout.EAST);
contentPane.add(buttonC, BorderLayout.WEST);
contentPane.add(display, BorderLayout.SOUTH);
// your codes
}
public static void main(String[] args) {
ActionTest f = new ActionTest();
f.setSize(200,100);
f.setVisible(true);
}
}
Q5)(25pts)
(a)
Write a method int second(String time) that returns the number of seconds represented by time.
The variable time is a String in format hh:mm:ss.
Here hh , mm, ss represent the hour, minute and second of the time respectively.
Example, "5:33:22" or "11:30:25".
The number of seconds can be calculated by
hh*60*60 + mm*60 + ss
The methods returns -1 if the string is not in correct format.
Hint any exception is a subclass of Exception.
(b)
I have a file named timetable.txt. Here is a sample content of the file:
11:30:00-14:30:00
15:00:00-18:25:00
8:30:05-19:30:45
11:00:07-11:30:08
2:55:31-3:40:21
|
Each line consists of
beginTime-endTime
Write a program to calculate the number of seconds in the given time periods and write the results to a file name "out.txt".
The number of seconds in a given period is
The number of seconds of endTime - the number of seconds of beginTime
11:30:00-14:30:00 10800 seconds
15:00:00-18:25:00 12300 seconds
8:30:05-19:30:45 39640 seconds
11:00:07-11:30:08 1801 seconds
2:55:31-3:40:21 2690 seconds
|
Error check:
- You can assume that the data in the files are in correct format, i.e., every line has 2 times seperated by "-" and all the times are in correct format.
- You can assume the beginTime is always earlier then the endTime.
- Whenever there is an IOException or FileNotFoundException, simply exit the program.
public class TimeCal {
public static int second(String time) {
// your codes for part (a)
}
public static void main(String[] args) {
// your codes for part (b)
}
}
Q6)(25pts)
You are going to write simple game to teach children names of different colors.
The program randomly choose a color name. The user then try to click on the correct color.
1.

- The program starts with 8 buttons with different colors on them (red, blue, yellow, green, pink, black, white, orange).
- a random color name is chosen and is shown on the
topLabel
- The user can click on the color buttons or the
nextButton
2.

The user clicked on a button with a wrong color:
- a message was shown on the
correctLabel
3.

The user clicked on the correct button:
- a message was shown on the
correctLabel
4.

- The user can click on the
nextButton anytime (after a correct answer or a wrong answer) to get a new question.
- The message on
correctLabel disappears
- new color name is chosen by random
Recall
Math.random() returns a double between 0 and 1
Fill in the codes below
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ColorGame extends JFrame implements ActionListener {
private Color[] colors = {Color.red, Color.blue, Color.yellow, Color.green,
Color.pink, Color.black, Color.white, Color.orange};
private String[] name = {"red", "blue", "yellow", "green",
"pink", "black", "white", "orange"};
private JButton[] colorButton = new JButton[8];
private JLabel topLabel = new JLabel();
private JLabel correctLabel = new JLabel();
private JButton nextButton = new JButton("Next Question");
private JPanel colorPanel = ________________________________;
private JPanel bottomPanel = _______________________________;
private Container contentPane = getContentPane();
// other variables (if any)
public ColorGame() {
for(int i = 0; i < colorButton.length; i++) {
colorButton[i] = new JButton();
}
// your codes
bottomPanel.add(correctLabel);
bottomPanel.add(nextButton);
contentPane.add(topLabel, BorderLayout.NORTH);
contentPane.add(colorPanel);
contentPane.add(bottomPanel, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e) {
// your codes
}
// other methods (if any)
public static void main(String[] args) {
ColorGame game = new ColorGame();
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.setSize(290,140);
game.setVisible(true);
}
}