Question

In: Computer Science

public class Account{ public int bal; // this store the balance amount in the account public...

public class Account{

public int bal; // this store the balance amount in the account

public Account(int initialBalance)

{

bal = initialBalance;

}

public static void swap_1(int num1, int num2)

{

int temp = num1;

num1 = num2;

num2 = temp;

}

public static void swap_2(Account acc1, Account acc2)

{

int temp = acc1.bal;

acc1.bal = acc2.bal;

acc2.bal = temp;

}

public static void swap_3(Account acc1, Account acc2)

{

Account temp = acc1;

acc1 = acc2;

acc2 = temp;

}

}

Now, different students tried to use different swap_*() methods to swap the balances in their friends’ bank accounts. Predict the output of each of the following code snippets [1 pts each]

(a) Account tom = new Account(100);

Account jim = new Account(2000);

System.out.println(“1.Tom has $” + tom.bal + “Jim has $” + jim.bal);

swap_1(tom.bal, jim.bal);

System.out.println(“2.Tom has $” + tom.bal + “Jim has $” + jim.bal);



(b) Account tom = new Account(100);

Account jim = new Account(2000);

System.out.println(“1.Tom has $” + tom.bal + “Jim has $” + jim.bal);

swap_2(tom, jim);

System.out.println(“2.Tom has $” + tom.bal + “Jim has $” + jim.bal);



(c) Account tom = new Account(100);

Account jim = new Account(2000);

System.out.println(“1.Tom has $” + tom.bal + “Jim has $” + jim.bal);

swap_3(tom, jim);

System.out.println(“2.Tom has $” + tom.bal + “Jim has $” + jim.bal);




Section B: Fun with stacks [2 pts each question]

Consider a generic Stack class implemented using linked list with the following methods:

  • public boolean isEmpty(), which returns true if and only if the stack is empty;

  • public T pop() throws StackUnderflowException, which removes and returns the top element of the stack (if the stack is empty, it throws StackUnderflowException);

  • public T peek() throws StackUnderflowException, which returns the top element of the stack (but does not remove it; it throws exception if stack is empty);

  • public void push(T element), which pushes an element onto the stack

Predict the output of each of the following code snippets

(a) Stack<Integer> s = new Stack<Integer>();

try{

s.push(5);

s.push(10);

System.out.println(s.peek());

System.out.println(s.pop());

s.push(20);

System.out.println(s.pop());

}
catch(Exception e) { System.out.print(“An exception was thrown”); }





(b) Stack<Integer> s = new Stack<Integer>();

try{

s.push(5);

s.push(50);

System.out.println(s.pop());

System.out.println(s.pop());

System.out.println(s.peek());

s.push(30);

}
catch(Exception e) { System.out.println(“An exception was thrown”); }





(c) Stack<Integer> s = new Stack<Integer>();

try{

s.push(5);

System.out.println(s.pop());

System.out.println(s.isEmpty());

s.push(10);

s.push(43);

s.push(s.pop());

System.out.println(s.peek());

} catch(Exception e) {

System.out.println(“An exception was thrown”);

}





(d) Stack<Integer> s = new Stack<Integer>();

try {

s.push(5);

s.push(10);

while(!s.isEmpty())

{

System.out.println(s.peek());

}

}
catch(Exception e) { System.out.println(“An exception was thrown”); }






Section C: Implementing Stack using Linked List

In this section, you will implement a generic Stack class implemented using linked list. Assume the linked list node class is already defined as below:
public class LLNode<T> {
public LLNode<T> link;

public T info;

public LLNode(T in) { info = in; link = null; }

}

Note that both class variables are public so any outside class can access them directly. Also assume that class StackUnderflowException has been defined that inherits Java’s Exception class. Your task is to implement four methods in the generic class LinkedListStack<T>.

public class LinkedListStack<T> {

private LLNode<T> head; // head of linked list, also stack top pointer

public LinkedListStack() { head = null; } // constructor

public boolean isEmpty() { // [1 pts]

// TODO: return true if stack is empty, false otherwise

// NO MORE THAN 1 LINE OF CODE!

}

public void push(T element) { // [2 pts]

// TODO: push an element to the stack

// NO MORE THAN 3 LINES of CODE!

}

public T peek() throws StackUnderflowException { // [2 pts]

// TODO: return the top element of the stack (but do NOT
// remove it). NO MORE THAN 4 LINES of CODE!

}

public T pop() throws StackUnderflowException { // [3 pts]

// TODO: remove and return the top element of the stack

// It throws StackUnderflowException if stack is empty

// NO MORE THAN 6 LINES of CODE!

}

Solutions

Expert Solution

Section A

Predict the output of each of the following code snippets

============================================================================================

(a) Account tom = new Account(100);

Account jim = new Account(2000);

System.out.println(“1.Tom has $” + tom.bal + “Jim has $” + jim.bal);

swap_1(tom.bal, jim.bal);

System.out.println(“2.Tom has $” + tom.bal + “Jim has $” + jim.bal);

Output

1.Tom has $100Jim has $2000
2.Tom has $100Jim has $2000

Reason: swap_1() is passing arguments as call by value method. all changes will only in the local variable of swap_1() function.

============================================================================================

(b) Account tom = new Account(100);

Account jim = new Account(2000);

System.out.println(“1.Tom has $” + tom.bal + “Jim has $” + jim.bal);

swap_2(tom, jim);

System.out.println(“2.Tom has $” + tom.bal + “Jim has $” + jim.bal);

Output

1.Tom has $100Jim has $2000
2.Tom has $2000Jim has $100

Reason: swap_2() is passing objects as parameters. so all changes are done on variables of objects in swap_2(). so they got swap in real.

============================================================================================

(c)

Account tom = new Account(100);

Account jim = new Account(2000);

System.out.println(“1.Tom has $” + tom.bal + “Jim has $” + jim.bal);

swap_3(tom, jim);

System.out.println(“2.Tom has $” + tom.bal + “Jim has $” + jim.bal);

Output

1.Tom has $100Jim has $2000
2.Tom has $100Jim has $2000

Reason: swap_3() is passing objects as parameters. But in function, objects are swapped. so value dont got swapped. we get same as output.

============================================================================================


Related Solutions

public class Date { private int dMonth; //variable to store the month private int dDay; //variable...
public class Date { private int dMonth; //variable to store the month private int dDay; //variable to store the day private int dYear; //variable to store the year //Default constructor //Data members dMonth, dDay, and dYear are set to //the default values //Postcondition: dMonth = 1; dDay = 1; dYear = 1900; public Date() { dMonth = 1; dDay = 1; dYear = 1900; } //Constructor to set the date //Data members dMonth, dDay, and dYear are set //according to...
please recode this in c++ language public abstract class BankAccount { double balance; int numOfDeposits; int...
please recode this in c++ language public abstract class BankAccount { double balance; int numOfDeposits; int numOfWithdraws; double interestRate; double annualInterest; double monSCharges; double amount; double monInterest; //constructor accepts arguments for balance and annual interest rate public BankAccount(double bal, double intrRate) { balance = bal; annualInterest = intrRate; } //sets amount public void setAmount(double myAmount) { amount = myAmount; } //method to add to balance and increment number of deposits public void deposit(double amountIn) { balance = balance + amountIn;...
public class SinglyLikedList {    private class Node{        public int item;        public...
public class SinglyLikedList {    private class Node{        public int item;        public Node next;        public Node(int item, Node next) {            this.item = item;            this.next = next;        }    }       private Node first;    public void addFirst(int a) {        first = new Node(a, first);    } } 1. Write the method add(int item, int position), which takes an item and a position, and...
public class P2 { public static int F(int x[], int c) { if (c < 3)...
public class P2 { public static int F(int x[], int c) { if (c < 3) return 0; return x[c - 1] + F(x, c - 1); } public static int G(int a, int b) { b = b - a; a = b + a; return a; } public static void main(String args[]) { int a = 4, b = 1; int x[] = { 3, 1, 4, 1, 5 }; String s = "Problem Number 2"; System.out.println(x[2 +...
Suppose that Account class has private attributes double balance and two public methods void setBalance(double amount)...
Suppose that Account class has private attributes double balance and two public methods void setBalance(double amount) and double getBalance() const. The method names explain its purpose. Further suppose that child class Savings has one more attribute double interest_rate and a public method void addInterest() which will update the balance according the formula new balance = old balance * (1 + interest_rate/100.0); Implement addInterest method. c++
public class Clock { private int hr; private int min; private int sec; public Clock() {...
public class Clock { private int hr; private int min; private int sec; public Clock() { setTime(0, 0, 0); } public Clock(int hours, int minutes, int seconds) { setTime(hours, minutes, seconds); } public void setTime(int hours, int minutes, int seconds) { if (0 <= hours && hours < 24) hr = hours; else hr = 0; if (0 <= minutes && minutes < 60) min = minutes; else min = 0; if(0 <= seconds && seconds < 60) sec =...
package applications; public class Matrix { private int[][] m; public Matrix(int x, int y) { m...
package applications; public class Matrix { private int[][] m; public Matrix(int x, int y) { m = new int[x][y]; } public Matrix(int x, int y, int z) { m = new int[x][y]; for(int i = 0; i < x; i++) { for(int j = 0; j < y; j++) { m[i][j] = z; } } } public int rowsum(int i) throws IndexOutOfBoundsException { if (i < 0 || i > m.length-1) { throw new IndexOutOfBoundsException("Invalid Row"); } int sum =...
a. Define the class bankAccount to store a bank customer’s account number and balance. Suppose that...
a. Define the class bankAccount to store a bank customer’s account number and balance. Suppose that account number is of type int, and balance is of type double. Your class should, at least, provide the following operations: set the account number, retrieve the account number, retrieve the balance, deposit and withdraw money, and print account information. Add appropriate constructors. b. Every bank offers a checking account. Derive the class checkingAccount from the class bankAccount (designed in part (a)). This class...
7.3 (The Account class) Design a class named Account that contains: ■ A private int data...
7.3 (The Account class) Design a class named Account that contains: ■ A private int data field named id for the account. ■ A private float data field named balance for the account. ■ A private float data field named annualInterestRate that stores the current interest rate. ■ A constructor that creates an account with the specified id (default 0), initial balance (default 100), and annual interest rate (default 0). ■ The accessor and mutator methods for id, balance, and...
public class Problem1 {    public static void partition(int[] A)    {        /*Rearrange the...
public class Problem1 {    public static void partition(int[] A)    {        /*Rearrange the array to have the following property:        Suppose the first element in the original array has the value x.        In the new array, suppose that x is in position i, that is data[i] = x.        Then, data[j] <= x for all j < I and data[j] > x for all j > i.        Thus, informally, all the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT