Computer Science 157 – Spring 2002

03/28/02                             Mid Term Test # 2                     Test Form A

 

Name:

 

Instructions:

               Answer ALL questions on the answer sheet provided.

               Hand in TEST, Answer Sheet, and Help Sheet, each with your name on it.

               Remember to put the letter of your test form on your answer sheet.

               Please ask any clarifying questions you have (come up).

 

Multiple Choice (4 points each)

 

  1. Which of the following is true about Java methods?

A)     all methods must have a return statement

B)     all method names must start with a lowercase letter

C)     methods must always be defined inside a class definition

D)    all of the above

E)     none of the above

 

2.      Which of the following is true about variables in Java?

A)     A variable declared inside a method is only known (and thus legal to use) inside that method

B)     A variable declared inside a loop is only known (and thus legal to use) inside that loop

C)     A formal parameter to a method can be used inside the method much the same way as a variable in that method

D)    All of the above

E)     None of the above

 

 

Completion (3 points each)

 

  1. Classes in object-oriented programming support and enforce the idea of ________, in which details of how something works is kept privileged, so that the users do not worry about or depend upon the details.  The external aspects of an object, which can be viewed or accessed by other objects, are separate from the internal implementation details, which should be hidden from other objects.

 

4.      A(n) ________ method in Java changes the content (or part of the content) of an object. In other words, it can change the value(s) of instance variable(s).

  1. In Object-Oriented programming, objects are organized into categories, or ________ -- an abstraction of a group of similar objects. Data and actions are defined for each of these.

 

 

Short Answer (points as shown)

 

6.      Why are instance variables usually defined as private?

 

  1. For what kind(s) of problem solving situations are for loops well suited?

 

 


Valid/Invalid (4 points each)

For each, tell whether valid or invalid. If invalid, tell why!

Generally they are taken out of context, we assume that valid context surrounds them (e.g. inside a program, variables declared etc).  Comments are an attempt to inform you what type of situation we are dealing with.

 

8.

               /* in main */

int cnt = 0;

for (  ; cnt <= 5; cnt++)  {

               int sq = cnt * cnt;

System.out.println(cnt + “squared: “ + sq);

}

 

 

9.

               /* in main */

int cnt;

int total = 0;

for (cnt = 1; cnt <= 5; cnt++)
               total += cnt;

System.out.println(“total: “ + total);

 

 

10. /* For question  10, using the following method heading (part of class MyClass)

               public int junk (int x) { … 

    and the following  variable declarations in the main program

               MyClass silly = new MyClass();

               int now = 5;

              int next1;

    specify whether the method call ( in main) is valid or invalid – if invalid, explain why  

*/

 

next1 = silly.junk(int now);

 

 

11. Use the attached Thing class definition for the question 11.

 

/* in main */

Thing x = new Thing();

x.value = 4;

 

 

Doing and Understanding: (points as shown)

 

(8 points)

12. What is displayed on the screen when the following code fragment runs?

int cnt;

int cnt2;

for (cnt = 0; cnt < 2; cnt++) {

               for (cnt2 = 1; cnt2 < 5; cnt2 ++) {

                              System.out.println(cnt + “ | “ + cnt2);

               }

}

 

 


(9 points)

13. Given the Thing class defined at the back of the test, What is displayed on the screen when the following code fragment runs?

              

/* in main! */

Thing x = new Thing();

int a = 3;

x.setVal(a);

int b = 4;

int y = x.doStuff(b);

int z = x.doStuff(y);

System.out.println(“X:  “ +  x.getVal() + “ | Y: “ + y + “ |  Z: “ + z);

 

 

(10 points)

14. Given the attached Account class definition, Indicate the output from the following fragment of code:

 

    Account x = new Account();

    x.setAcctNum(“1234”);

    x.setBal(100);

    Account y = new Account();

    y.setAcctNum (“2222”);

    y.setBal(0);

    while (x.getBal( )  > y.getBal() ) {

               boolean trans;

               trans = x.withdraw(30);

               trans = y.deposit(30);

                System.out.println(“X:  “ +  x.getBal( ));

        }

     System.out.println(“X:  “ + x.getBal( ) + “|  Y: “ + y.getBal( ));

 

 

Writing Code (points as shown)

 

Use the HotDogStand class definition attached at the back of the test  for questions 15-16

 

(8 points)

15. Write the getTotProfit method for the HotDogStand class.

 

(20 points)

16. Write code for part of main that (assuming that a HotDogStand named myStand has already been defined and initialized (to starting with 100 hotdogs, 0 sold, and a profit margin of $0.50)), processes customers until 50 customers have been processed, and for each one, ask the customer for the number of hot dogs, and sell them if you can. (A customer who cannot be served is skipped and we move on to the next customer (e.g. if the first customer comes in and asks for 150 hot dogs, we tell them sorry and move on to the next customer).  After all 50 customers have been processed, (and as many customers have been served as possible), report the number of customers actually served and the total profits for the day.


Attached Classes

 

public class Thing {

               public Thing() {

}

               public int getVal() {

                              return value;

               }

               public void setVal(int val) {

                              value = val;

               }

               public int doStuff(int junk) {

                              return value + junk;

               }

               private int value;

               }

 

 

public class HotDogStand {

 

private int numStart;    // number hotdogs started with

               private int numSold;   // number of hotdogs sold

               private double profitMargin;   // profit per hotdog

 

     public HotDogStand () {

}    // default HotDogStand constructor

     public void setStart(int num) {

               numStart = num;

               }

     public void setSold(int num) {

               numSold = num;

               }

     public void setMargin(double val) {

               profitMargin = val;

               }

     public int getStart()  {  // report hot dog stand’s starting inventory

               return numStart;

               }

     public int getSold( ) { // report hot dog stand’s number sold

               return numSold;

               }

     public double getMargin() { // report profit margin per hotdog

               return profitMargin;

               }

     public double getTotProfit( ) { // report total profit earned

               // code saved to be written by students

               }

     public int getCurrInv ( ) {  // report current inventory amount

               int remain = numStart – numSold;

               return remain;

               }

     public boolean sellDog(int num) {  // sell hotdog(s), reporting true if sale successful, false if failed (no dogs avail)

               // code saved to be written by students

               }

}


public class Account {

 

    protected String acctNum;

    protected String PIN;

    protected double balance = 0;

    protected double intRate = 0.03;

   

    /** Creates new Account */

    public Account() {

    }

 

    // deposit a given amount into the calling Account

    public boolean deposit(double amt) {

        // reject a negative deposit

        if (amt <= 0) {

            System.out.println("PROGRAM ERROR - cannot deposit negative amount");

            return false;

        }

        else {

            balance = balance + amt;

            return true;

        }

    }

   

    // withdraw a given amount from the calling account

    public boolean withdraw(double amt) {

        // reject a negative wothdrawal

        if (amt <= 0) {

            System.out.println("PROGRAM ERROR - cannot withraw a negative amount");

            return false;

        }

        else if (amt > balance) {

            System.out.println("ERROR - cannot withraw an amount more than in account");

            return false;

        }

        else {

            // can withdraw

            balance = balance - amt;

            return true;

        }

    }

   

    /* pay interest at the percent appropriate for the account, for a given number of days */

    public double payInterest (int numDays) {

                              if (numDays <= 0) {

                                             System.out.println("ERROR - invalid number of days");

                        // no interest if no days or fewer

                                             return 0;

                              }

                              double intAmt = balance * (intRate * (numDays / 365.0));

                              balance += intAmt;

                              return intAmt;

               }


   public boolean payInterestfirstVersion (int numDays) {

                              if (numDays <= 0) {

                                             System.out.println("ERROR - invalid number of days");

                                             return false;

                              }

                              double intAmt = balance * (intRate * (numDays / 365.0));

                              balance += intAmt;

                              return true;

               }

   

    // return the current balance - basically an account inquiry

    public double getBal() {

        return balance;

    }

   

    // return the account number

    public String getAcctNum() {

        return acctNum;

    }

   

    // report the PIN

    public String getPin() {

        return PIN;

    }

   

    // return the current interest rate

    public double getIntRate() {

        return intRate;

    }

   

    // set the account balance  

    public boolean setBal(double amt) {

        // reject negative balance

        if (amt < 0) {

            System.out.println("PROGRAM ERROR - cannot set a negative account balance");

            return false;

        }

        else {

            balance = amt;

        }

        return true;

    }

   

    // set account number 

    public boolean setAcctNum(String acctNumber) {

        acctNum = acctNumber;

        // could check acct number to see if it is valid (check digit or already in DB) but for now just say that it is ok

        return true;

    }

   

    // set PIN - should be carefully controlled

    public boolean setPIN(String pin) {

        PIN = pin;

        // could check PIN based on some PIN rules - but for now just say

        // that it is ok

        return true;

    }

   

    // Second, we need a way of setting the interest rate

               public void setIntRate (double rate) {

                              intRate = rate;

               }

   

    // determine if a passed string is the correct account number for the calling object

    public boolean matchAcctNum(String toCompare) {

        if (acctNum.equals(toCompare)) {

            return true;

        }

        else {

            return false;

        }

    }

   

    // determine if a passed account has the same account number as the calling object

    public boolean matchAcctNum(Account toCompare) {

        if (acctNum.equals(toCompare.getAcctNum())) {

            return true;

        }

        else {

            return false;

        }

    }

   

    // determine if a passed account has the same contents as the

    // calling object (account number, PIN, AND balance)

    public boolean equals(Account toCompare) {

        if ( acctNum.equals(toCompare.getAcctNum())

             && PIN.equals(toCompare.getPin())

             && balance == toCompare.getBal() ) {

            return true;

        }

        else {

            return false;

        }

    }

   

    // produce a string for an account - generally used for display

    public String toString() {

        String res = "Acct: " + acctNum + " PIN: " + PIN

                + " Bal: " + balance;

        return res;

    }

   

}