Quiz 4 Solution

  1. Terms and Concepts

    (a)
    A String object is immutable (i.e. it can't be changed).
    A StringBuffer object is mutable (i.e. it can be changed).

    str1 == str2 compares the addresses of str1 and str2; it returns true only if str1 and str2 are referring to the same object.
    str1.equals(str2) compares the contents of str1 and str2; it returns true only if str1 and str2 contain the same characters (in the same order).

    (b)
    1. primitive
    2. reference
    3. address (also acceptable: reference, memory location)

  2. Code Tracing
    student18:20
    student18:16
    student18:14
    student14:14
    student12:14
    student12:12
    
  3. Code Writing (code in green was given)
    public void runningBalance(MainWindow mw) {
       InputBox in = new InputBox(mw);
       OutputBox out = new OutputBox(mw);
       int balance = in.getInteger("Enter the initial balance:");
    
       out.show();
       String ans;
       int amount;
       boolean again = true;
    
       do {
          ans = in.getString("Deposit (d), withdraw (w), or quit (q)?");
          switch (ans.charAt(0)) {
    
             case 'd':
             case 'D':
                amount = in.getInteger("How much do you want to deposit?");
                if (amount < 0)
                   out.printLine("Cannot deposit negative amount");
                else {
                   balance += amount;
                   out.printLine("Current balance: " + balance);
                }
                break;
    
             case 'w':
             case 'W':
                amount = in.getInteger("How much do you want to withdraw?");
                if (amount < 0)
                   out.printLine("Cannot withdraw negative amount");
                else {
                   balance -= amount;
                   out.printLine("Current balance: " + balance);
                }
                break;
    
             case 'q':
             case 'Q':
                out.printLine("Final balance: " + balance);
                again = false;
    
             default:
                out.printLine("Please enter d, w, or q");
    
          } // end switch
       } while (again);	
    } // end method runningBalance