Add a toString method to the BanAccount class from the previous exercise. your m
ID: 3554061 • Letter: A
Question
Add a toString method to the BanAccount class from the previous exercise. your method should return a strin that contains the accoun'ts name and the balance separted by a comma and space. for exameple , if an account object named yana has name "Yana" and blance of 3.03, the call yana.toString() should return string "Yana, $3.03".
here is the code from the previoust exercise!!
public class banckAccount {
String name ;
double balance;
public void deposit (double amount ){
balance = blance + amount ;
}
public void Withdraw (double amount ){
balance = balance - amount ;
}
}
i was traying this :
public String toString() {
return name + ", " + "$"+balance;
}
it works with some names as
Marty, $123.45
but when i type in
"Bankrupt Government, -$765432.10"
i get :
"Bankrupt Government, $-765432.1"
Explanation / Answer
import java.text.DecimalFormat;
public class banckAccount
{
String name ;
double balance;
public banckAccount (String s, double i)
{
name = s;
balance = i;
}
public void deposit (double amount )
{
balance = balance + amount ;
}
public void Withdraw (double amount )
{
balance = balance - amount ;
}
public String toString()
{
DecimalFormat df = new DecimalFormat("#.00");
return name + ", " + "$"+df.format(balance);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.