Problems using the toString method in Java [closed]

余生长醉 提交于 2019-12-12 04:05:16

问题


I'm working on a banking program that is supposed to use 3 classes (Account-base class, CheckingAccount, and SavingsAccount) and several methods to display the banking information (ID, balance after a withdrawal and deposit, and the annual interest rate). This should be a pretty simple program, but I'm getting hung up on one portion of it. In the 2 subclasses (CheckingAccount and SavingsAccount) we are told to "invoke their toString() methods" We briefly hit on the topic of overrides and toString() methods in class, but there's not a whole lot in our textbook on the topic and I'm having some trouble figuring out how to do this as it applies to my particular program?

Here is the code I have so far (haven't tested it to see if it works yet since I'm still trying to get the toString() methods in there, but other than that I THINK it's almost done).

import java.util.Date;

public class Account {
    private int id = 0;
    private double balance = 0;
    private double annualInterestRate = 0;
    private Date dateCreated = new Date();

    public Account() {
      id = 0;
      balance = 0.0;
      annualInterestRate = 0.0;
    }

    public Account(int newId, double newBalance) {
      id = newId;
      balance = newBalance;
    }

    public int getId() {
      return id;
    }

    public double getBalance() {
      return balance;
    }

    public double getAnnualInterestRate() {
      return annualInterestRate;
    }

    public int setId(int newId) {
      id = newId;
    }

    public double setBalance(double newBalance) {
      balance = newBalance;
    }

    public double setAnnualInterestRate(double newAnnualInterestRate) {
      annualInterestRate = newAnnualInterestRate;
    }

    public java.util.Date getDateCreated() {
      return dateCreated;
    }

    public double getMonthlyInterestRate() {
      return annualInterestRate/12;
    }

    public void withdrawal (double withdrawalAmount) {
      return balance -= withdrawalAmount;
    }

    public void deposit (double depositAmount) {
      return balance += depositAmount;
    }

  public static void main(String[] args) {
    //System.out.println("Account Created!");
    //System.out.println("Savings Account: " + savingsAccount.getId() + "Balance: $%1.2f." + savingsAccoung.getBalance() + "Rate: " + savingsAccoung.getAnnualInterestRate() + "%");
    //System.out.println("Checking Account: " + checkingAccount.getId() + "Balance: $%1.2f." + checkingAccount.getBalance() + "Rate: " + checkingAccount.getAnnualInterestRate() + "%");

  }
}

Here's my CheckingAccount class:

public class CheckingAccount extends Account {
  Account checkingAccount = new Account(1271, 150);
  checkingAccount.setAnnualInterestRate(1.25);
  checkingAccount.withdrawal(300);
  checkingAccount.deposit(500);
  double overdraft = 200;

  public String toString() {
    return 
  }

And here's my SavingsAccount class:

public class SavingsAccount extends Account {
    Account savingsAccount = new Account(1122, 20000);
    savingsAccount.setAnnualInterestRate(4.5);
    savingsAccount.withdrawal(5000);
    savingsAccount.deposit(10000);

}

If it helps, the final output is supposed to look something like this:

Account Created!
Savings Account ID: 1122 Balance: $20000.00 Rate: 4.5%
Checking Account ID: 1271 Balance: $150.00 Rate: 1.25%
Updating Interest
Savings Account ID: 1122 Balance: $20900.00 Rate: 4.5%
Checking Account ID: 1271 Balance: 151.88 Rate: 1.25%
Processing Withdrawals
Savings Account ID: 1122 Balance: $15900.00 Rate: 4.5%
Checking Account ID: 1271 Balance: $... Rate: 1.25$ Overdraft
Processing Deposits
Savings Account ID: 1122 Balance:... Rate: 4.5%
Checking Account ID: 1271 Balance:... Rate: 1.25%
Thank you for your business!

Any suggestions would be very much appreciated.

Update Would the toString() method look something like the following?

public String toString() {
    return ID: + id + Balance: + balance + Rate: + annualInterestRate;
  }

I guess the thing that's really confusing me is how to use the two toString() methods (one for each subclass) to print the output like it's laid out in the example?

Update Here is my most up-to-date code, I'm still getting some compiler errors, all of which deal with non-static variables being called from a static context (I'll also post these errors following the code). Up until the middle of last week, we just declared everything as static, but that's changed and I'm having trouble figuring out when to and when not to use static when declaring my methods, hence the compiler errors.

I was told once that replacing the original code with the updated code can make the answers look bad, so I'm just adding my current code, I hope that's ok.

import java.util.Date;

public class Account {
    private int id = 0;
    private double balance = 0;
    private double annualInterestRate = 0;
    private Date dateCreated = new Date();

    public Account() {
      id = 0;
      balance = 0.0;
      annualInterestRate = 0.0;
    } 

    public Account(int newId, double newBalance) {
      id = newId;
      balance = newBalance;
    }

    public int getId() {
      return id;
    }

    public double getBalance() {
      return balance;
    }

    public double getAnnualInterestRate() {
      return annualInterestRate;
    }

    public void setId(int newId) {
      id = newId;
    }

    public void setBalance(double newBalance) {
      balance = newBalance;
    }

    public void setAnnualInterestRate(double newAnnualInterestRate) {
      annualInterestRate = newAnnualInterestRate;
      balance = balance * annualInterestRate;
    }

    public java.util.Date getDateCreated() {
      return dateCreated;
    }

    public double getMonthlyInterestRate() {
      return annualInterestRate/12;
    }

    public double withdrawal (double withdrawalAmount) {
      return balance -= withdrawalAmount;
    }

    public double deposit (double depositAmount) {
      return balance += depositAmount;
    }

  public static void main(String[] args) {
    Account savingsAccount = new Account(1122, 20000);
    Account checkingAccount = new Account(1271, 150);
    System.out.println("Accounts Created!");
    System.out.println(savingsAccount);
    System.out.println(checkingAccount);
    savingsAccount.setAnnualInterestRate(4.5);
    checkingAccount.setAnnualInterestRate(1.25);
    System.out.println("Updating Interest");
    System.out.println(savingsAccount);
    System.out.println(checkingAccount);
    savingsAccount.withdrawal(5000);
    checkingAccount.withdrawal(300);
    System.out.println("Processing Withdrawal");
    System.out.println(savingsAccount);
    System.out.println(checkingAccount);
    savingsAccount.deposit(10000);
    checkingAccount.deposit(500);
    System.out.println("Processing Deposit");
    System.out.println(savingsAccount);
    System.out.println(checkingAccount);
    System.out.println("Thank you for your business!");
    }
  }

public class CheckingAccount extends Account {
  public static void main(String[] args) {
    //double overdraft = 200;
  }
    @Override
    public String toString() {
      return "Checking Account: ID: " + Account.getId() + "Balance: " + Account.getBalance() + "Rate: " + Account.getAnnualInterestRate();
    } 
} 

public class SavingsAccount extends Account {
  public static void main(String[] args) {
  }
    @Override
    public String toString() {
      return "Savings Account: ID: " + Account.getId()+ "Balance: " + Account.getBalance() + "Rate: " + Account.getAnnualInterestRate();
    } 
} 

Here are the compiler errors I am receiving:

Compilation completed.  The following files were not compiled:
6 errors found:
File: C:\Users\HiTechRedneck\Desktop\Summer II 2014\Computer Programming Principle\Program 5\CheckingAccount.java  [line: 7]
Error: non-static method getBalance() cannot be referenced from a static context
File: C:\Users\HiTechRedneck\Desktop\Summer II 2014\Computer Programming Principle\Program 5\CheckingAccount.java  [line: 7]
Error: non-static method getAnnualInterestRate() cannot be referenced from a static context
File: C:\Users\HiTechRedneck\Desktop\Summer II 2014\Computer Programming Principle\Program 5\SavingsAccount.java  [line: 6]
Error: non-static method getId() cannot be referenced from a static context
File: C:\Users\HiTechRedneck\Desktop\Summer II 2014\Computer Programming Principle\Program 5\SavingsAccount.java  [line: 6]
Error: non-static method getBalance() cannot be referenced from a static context
File: C:\Users\HiTechRedneck\Desktop\Summer II 2014\Computer Programming Principle\Program 5\SavingsAccount.java  [line: 6]
Error: non-static method getAnnualInterestRate() cannot be referenced from a static context

回答1:


From the docs:

Every class has Object as a superclass.

And the java.lang.Object class has the method toString() in it. This means that every class you create can use that method, even if it's not overridden (it's inherited). When you print the object, it prints the return of that method, toString().

So for example, when you write this:

Account account1 = new Account();
System.out.println(account1);

It's the same as this:

Account account1 = new Account();
System.out.println(account1.toString());

What your instructor wants you to do is override that toString() method that is automatically inherited so that you may customize what happens when you print out the object.

For example (add this to your Account class):

@Override
public String toString() {
    return "ID: "+id+" "+"Balance: "+balance+" "+"Rate: "+annualInterestRate;
}

Normally the toString() method (if not overridden) prints this:

getClass().getName() + '@' + Integer.toHexString(hashCode())

But now that you've overridden it, it should print this:

"ID: " + id + " " + "Balance: " + balance + " " + "Rate: " + annualInterestRate


来源:https://stackoverflow.com/questions/24987061/problems-using-the-tostring-method-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!