Debug the java code below to get working correctly. Both .java file are pasted b
ID: 3759072 • Letter: D
Question
Debug the java code below to get working correctly. Both .java file are pasted below, thanks!
class Account
{
// Instance variables
private double balance; // invariant: balance >= 0 (should never be negative)
private String owner;
//Constructor
public Account(String name)
{
balance = 0;
owner = name;
}
// Instance methods
/** Deposits 'amount' into the account
*/
public void deposit(int amount)
{
balance = balance + amount;
}
/** Withdraws 'amount' from the account.
* This only makes sense if amount <= balance.
* This method should be re-written so that there is not a possibility of
* having a negative balance.
*/
public void withdraw(int amount)
{
balance = balance - amount;
}
/* Returns the balance of the Account
*/
public int getBalance()
{
return balance;
}
/* Returns the owner of the Account
*/
public String getOwner()
{
return owner;
}
}
class DebuggingExercise4
{
public static void main(String[] args)
{
Account a = null;
a.deposit(100);
System.out.println(a.getOwner() + " has $" + a.getBalance());
a.withdraw(200);
System.out.println("After trying to withdraw $200, " + a.getOwner() + " has $" + a.getBalance());
}
}
Explanation / Answer
class Account
{
// Instance variables
private double balance; // invariant: balance >= 0 (should never be negative)
private String owner;
//Constructor
public Account(String name)
{
balance = 0;
owner = name;
}
// Instance methods
/** Deposits 'amount' into the account
*/
public void deposit(int amount)
{
balance = balance + amount;
}
/** Withdraws 'amount' from the account.
* This only makes sense if amount <= balance.
* This method should be re-written so that there is not a possibility of
* having a negative balance.
*/
public void withdraw(int amount)
{
balance = balance - amount;
}
/* Returns the balance of the Account
*/
public double getBalance()
{
return balance;
}
/* Returns the owner of the Account
*/
public String getOwner()
{
return owner;
}
}
class DebuggingExercise4
{
public static void main(String[] args)
{
Account a = new Account("sample");
a.deposit(100);
System.out.println(a.getOwner() + " has $" + a.getBalance());
a.withdraw(200);
System.out.println("After trying to withdraw $200, " + a.getOwner() + " has $" + a.getBalance());
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.