PIC20A Final Exam

Instructions

  1. The exam consists of 17 pages(including this page). You are responsible for checking the number of pages
  2. Please read and answer all the questions carefully. The point value for each question in indicated. The total number of points available is 112. If you have trouble with a question, leave it and try another.
  3. 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.
  4. Good luck!




Last Name:_________________ First Name:________________
Student ID:_________________











Question Q1 Q2 Q3 Q4Q5 Q6Q7 Q8Q9 Total(112pts)
Score



























Q1)(16pts)
(a) After the following code has been executed, what will be the first element of the arrary?
String[] array = new String[20];
Answer:_______________________________________________________

(b)
What is the output of the following program?
   1:public class EqualTest {
   2:    public static void main(String[] args) {
   3:        Double d1 = new Double(3.14);
   4:        Double d2 = new Double(3.14);
   5:        if(d1 == d2) {
   6:            System.out.println("equal");
   7:        } else {
   8:            System.out.println("not equal");
   9:        }
  10:    }
  11:}
  12:
Answer:_______________________________________________________

(c)
What is the output of the following program?
   1:public class MethodCall {
   2:    public static void increase(Integer x) {
   3:        x = new Integer(x.intValue()+1);
   4:    }
   5:    
   6:    public static void main(String[] args) {
   7:        Integer x = new Integer(5);
   8:        increase(x);
   9:        System.out.println(x);
  10:    }
  11:}
Answer:___________________________________________________________

(d)
What is the output of the following program?
   1:public class ForTest {
   2:    public static void main(String[] args) {
   3:        for(int i=0, j=1; i<=2 && j<=3; i++, j++) {
   4:            System.out.print("(" + i + "," + j+ ")" + " ");
   5:        }
   6:    }
   7:}
Answer:____________________________________________________________________________

(e)
Circle the correct answer:
You execute the code below in an empty directory. What is the result?
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.

(f)
Assume this class hierarchy:
                   Animal
                     |
                   Mammal
                     |
  --------------------------------------------
  |           |              |               |
 Dog         Cat          Raccoon       SwampThing
         (implements    (implements
            Washer)       Washer)
(i)
Consider the following code:
1. Dog      rover, fido;
2. Animal   anim;
3.
4. rover = new Dog();
5. anim = rover;
6. fido = (Dog)anim;
Which of the statements below is true? (Choose one.)
A) Line 5 will not compile
B) Line 6 will not compile
C) The code will compile but will throw an exception at line 6.
D) The code will compile and run.
E) The code will compile and run, but the cast in line 6 is not required and can be eliminated.

(ii)
Consider the following code:
1. Cat sunflower;
2. Washer wawa;
3. SwampThing pogo;
4.
5. sunflower = new Cat();
6. wawa = sunflower;
7. pogo = (SwampThing)wawa;
Which of the statements below is true? (Choose one.)
A) Line 6 will not compile; an explicit cast is required to convert a Cat to a Washer.
B) Line 7 will not compile, because you cannot cast an interface to a class.
C) The code will compile and run, but the cast in line 7 is not required and can be eliminated.
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 wawa cannot be converted to type SwampThing.

(g)
What is the output of the following program?
   1:public class StaticTest {
   2:    public static int x = 5;
   3:    public int y = 9;
   4:    
   5:    public static void main(String[] args) {
   6:        StaticTest test1 = new StaticTest();
   7:        StaticTest test2 = new StaticTest();
   8:        StaticTest.x++;
   9:        test1.x++;
  10:        test1.y++;
  11:        System.out.println("test1.x is " + test1.x);
  12:        System.out.println("test1.y is " + test1.y);
  13:        System.out.println("test2.x is " + test2.x);
  14:        System.out.println("test2.y is " + test2.y);      
  15:    }
  16:}
Answer









(h)
What is the output of the following program?
   1:public class WhileTest {
   2:    public static void main(String[] args) {
   3:        String s = "exam";
   4:        int i = 3;
   5:        while(i >= 0) {
   6:            System.out.print(s.charAt(i) + ",");
   7:            i--;
   8:        }     
   9:    }
  10:}
Answer:_____________________________________________________________________________________


Q2)(10pts)
(a)
Sketch(draw) the output of the following program
   1:import java.awt.*;
   2:import javax.swing.*;
   3:
   4:public class LayoutTest1 {
   5:    public static void main(String[] args) {
   6:        JFrame f = new JFrame("LayoutTest1");
   7:        f.getContentPane().setLayout(new GridLayout(2,4));
   8:        for(char ch = 'a'; ch <= 'g'; ch++) {
   9:            f.getContentPane().add(new JButton("" + ch));
  10:        }
  11:        f.getContentPane().remove(3);
  12:        f.getContentPane().add(new JButton(""+1), 5);
  13:        f.pack();
  14:        f.setVisible(true);
  15:    }
  16:}
Answer:



















(b)
Sketch(draw) the output of the following program
   1:import java.awt.*;
   2:import javax.swing.*;
   3:
   4:public class LayoutTest2 {
   5:    public static void main(String[] args) {
   6:        JFrame f = new JFrame();
   7:        f.getContentPane().setLayout(new BorderLayout());
   8:        JPanel panel = new JPanel(new GridLayout(2,0));
   9:        for(char ch = 'a'; ch <= 'f'; ch++) {
  10:            panel.add(new JButton("" + ch));
  11:        }
  12:        f.getContentPane().add(new JButton("Hi"), BorderLayout.EAST);
  13:        f.getContentPane().add(new JButton("Hey"));
  14:        f.getContentPane().add(panel, BorderLayout.NORTH);
  15:        f.setSize(300,300);
  16:        f.setVisible(true);
  17:    }
  18:}




















Q3)(12 pts)
For the following program:
   1:public class ExTest {
   2:    public static void main(String[] args) {
   3:        try{
   4:            int num1 = Integer.parseInt(args[0]);
   5:            System.out.println("Hello A");
   6:            int num2 = Integer.parseInt(args[1]);
   7:            System.out.println("Hello B");
   8:            int result = num1/num2;
   9:            System.out.println("Result is " + result);
  10:        } catch (NullPointerException ex) {
  11:            System.out.println("Error 1");
  12:        } catch(ArrayIndexOutOfBoundsException ex) {
  13:            System.out.println("Error 2");
  14:        } catch (ArithmeticException ex) {
  15:            System.out.println("Error 3");
  16:        } catch (NumberFormatException ex) {
  17:            System.out.println("Error 4");
  18:        } finally {
  19:            System.out.println("Hello C");
  20:        }
  21:        System.out.println("Hello D");
  22:    }
  23:}
Write down the output of
a) java ExTest













b) java ExTest abc












c) java ExTest 11












d) java ExTest 35 abc












e) java ExTest 7 2












f) java ExTest 10 0












Q4)(10 pts)
Suppose Vector v is a vector consists of Strings. Write a short method to find the number of strings in vector v that contains a given substring.
example, if v consists of "abcdef", "bcdefg", "defghi", then
Fill in the codes. You can assume the vector v consists of Strings only.
import java.util.*;

public class CountString {
    // return the number of strings in vector v that contain the given substring
    public static int countString(Vector v, String substring) {
        // your codes
        
























} }
(Q5)(12pts)
For the following programs, if there are compiler errors, circle and correct them. If there is no compiler error, write "no error".
(a)
   1:import java.io.*;
   2:
   3:public class ProgramA {
   4:    public static void writeString(OutputStream out,  String s) {
   5:        if(out !=null) {
   6:            for(int i = 0; i < s.length(); i++) {
   7:                int x = s.charAt(i);
   8:                out.write(x);
   9:            }
  10:        } 
  11:    }
  12:    
  13:    public static void main(String[] args) {
  14:        writeString(System.out, "hello");
  15:    }
  16:}
Correction:













(b)
   1:public class ProgramB {
   2:    public static void main(String[] args) {
   3:        try {
   4:            double a = Double.parseDouble(args[0]);
   5:            double c = a/0;
   6:        } catch (NumberFormatException ex) {
   7:            // do nothing
   8:        }
   9:        
  10:        if(a > 10000) {
  11:            System.out.println("args[0] is bigger than 10000.");
  12:        }
  13:    }
  14:}
Correction:













(c)
   1:import java.util.*;
   2:
   3:public class ProgramC {
   4:    public static void main(String[] args) {
   5:        LinkedList list = new LinkedList();
   6:        for(int i = 0; i < args.length; i++) {
   7:            list.add(args[i]);
   8:        }
   9:        
  10:        int[] array = {1,2,3};
  11:        for(int i = 0; i < array.length; i++) {
  12:            list.add(array[i]);
  13:        }
  14:    }
  15:}
Correction:













(d)
   1:import java.util.*;
   2:import java.awt.*;
   3:
   4:public class ProgramD {
   5:    private LinkedList list = new LinkedList();
   6:    
   7:    public ProgramD() {
   8:        list.add(Color.red);
   9:        list.add(Color.blue);
  10:        list.add(Color.green);
  11:    }
  12:    
  13:    public Color firstColor() {
  14:        return list.get(0);
  15:    }
  16:}
Correction:













(e)
   1:public class ProgramE {
   2:   public static void main(String[] args) {
   3:       double x = 5.3, y =7.7;
   4:       int sum; // you are not allowed to change this line
   5:       sum = x + y;
   6:   }
   7:}
Correction:













(f)
   1:import java.awt.*;
   2:import javax.swing.*;
   3:
   4:public class ProgramF {
   5:    public static void main(String[] args) {
   6:        JFrame f = new JFrame();
   7:        Container c = f.getContentPane();
   8:        JLabel label = new JLabel("ABC");
   9:        label.setVerticalTextPosition(5);
  10:        c.add(label);
  11:        f.pack();
  12:        f.setVisible(true);
  13:    }
  14:}
Correction:













Q6)(10 pts)
Write a method that returns the number of files in a given folder with the given extension.
The method int count(File f, String extension) returns You can assume there is no other folders inside the folder f Example
In a folder named hw4, there are 6 files 
a1.jpg, a2,jpg, a3.jpg, a4.jpg,  hw4.java, hw4.class
Hint : use endsWith method in String class.
Assume all the necessary packages are imported, fill in your codes
int count(File f, String ext) {
    //  your codes
    






















}
Q7)(10pts) Write an applet that shows a JLabel. The applet reads 4 parameters: Here is a sample html file.
   1:<html>
   2:<body>
   3:<applet code="ColorLabel.class" height="50" width="150"> 
   4:<param name="text" value="hello">
   5:<param name="red" value="120">
   6:<param name="green" value="180">
   7:<param name="blue" value="0">
   8:</applet>
   9:</body>
  10:</html>
Here is the output of the applet

Fill in the missing codes
import java.applet.*;
import java.awt.*;
import javax.swing.*;

public class ColorLabel extends Applet {
    public void init() {
         // your codes
         



















} }
Q8) (16 pts)
The program WhoAmI.java randomly gives a Simpson character name. The user then asked to click the correct picture.
All the images belows are inside a folder name simpson

Apu.gif

Bart.gif

Burns.gif

Homer.gif

Krusty.gif

Lisa.gif

Maggie.gif

Marge.gif

Moe.gif

Ned.gif
At the beginning:
Answer the question on the top label.
Each time, a character name is randomly chosen among the 10 names given above.


Click on the button with Lisa.

Number of trials is increased by 1. Number of correct answers is increased by 1.
Another question appears.

Click on a wrong button.

Number of trials is increased by 1 but number of correct answers remains unchanged.
Another question appears.
The game goes on forever.


In below is part of the codes. Fill in the missing codes.
import javax.swing.*;
import java.awt.event.*;

public class WhoAmI extends JFrame implements ActionListener {
    private JLabel topLabel = new JLabel();
    private JLabel bottomLabel = new JLabel();
    private JPanel middlePanel;
    private JButton[] buttons;
    private Container contentPane = getContentPane();
    private String[] names = {"Apu", "Bart", "Burns", "Homer", "Krusty",
                                "Lisa", "Maggie", "Marge", "Moe", "Ned"};
    // other variables 
    




public WhoAmI() { // your codes


































} public void actionPerformed(ActionEvent e) { // your codes


































} // other codes







































public static void main(String[] args) { JFrame f = new WhoAmI(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(280,180); f.setVisible(true); } }
Q9) (16 pts)
File score.txt consists student ID, homework scores, midterm scores and final scores.
The first colume is student ID. The next 5 columns are scores for hw1, hw2, ..., hw5. The next column is the midterm score and the final column is the final exam score. The scores are seperated by a tab ('\t').
Here is a sample file
score.txt
402532413       5.5     9       9       9       8.5     47.5    98.5
521834001      7.5     8       7.5     7.5     3.5     33      55
902222333       8       10      10      10      10      38      78
818666444       2       2.5     3.2     5       5.5     25      44
102456456       9       9       9       9       8.5     40      88.5     
The final result is then calculated by the following formula
0.6*hw1 + 0.6*hw2 + 0.6*hw3 + 0.6*hw4 + 0.6*hw5 + 0.5*midterm + 0.45*final
Write a program that reads scores from score.txt, calculates the final result, then saves Students IDs and final results in a file named result.txt. Student ID and the final result are seperated by a tab ('\t').
Here is the output of the sample file after running the program.
result.txt
402532413	92.675
521834001	61.65
902222333	82.9
818666444	43.22
102456456	86.525
You can assume In other word, you don't have to take care of any exception.
Fill in the missing codes:
import java.util.*;
import java.io.*;

public class FinalScore {
    public static void main(String[] args) throws IOException {
        String inFile = "score.txt";
        String outFile  = "result.txt";
        // your codes
        












































} }