Java中使用toString方法的问题

Java中使用toString方法的问题

问题描述:

我正在开发一个银行程序,它应该使用 3 个类(Account 基类、CheckingAccount 和 SavingsAccount)和几种方法来显示银行信息(ID、取款和存款后的余额以及年度利率).这应该是一个非常简单的程序,但我对它的一部分感到困惑.在 2 个子类(CheckingAccount 和 SavingsAccount)中,我们被告知调用它们的 toString() 方法"我们在类中简要讨论了覆盖和 toString() 方法的主题,但我们的教科书中没有太多关于该主题的内容和我在弄清楚如何执行此操作时遇到了一些麻烦,因为它适用于我的特定程序?

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?

这是我到目前为止的代码(还没有测试它是否有效,因为我仍在尝试在那里获取 toString() 方法,但除此之外我认为它几乎完成了).

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() + "%");

  }
}

这是我的 CheckingAccount 类:

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 
  }

这是我的 SavingsAccount 类:

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!

非常感谢任何建议.

更新toString() 方法会像下面这样吗?

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

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

我想真正让我困惑的是如何使用两个 toString() 方法(每个子类一个)来打印输出,就像它在示例中的布局一样?

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?

更新这是我最新的代码,我仍然遇到一些编译器错误,所有这些错误都处理从静态上下文调用的非静态变量(我还将在代码之后发布这些错误).直到上周中旬,我们才将所有内容都声明为静态,但这已经改变了,我无法弄清楚在声明我的方法时何时该使用以及何时不使用 static,因此出现了编译器错误.

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

来自 文档:

每个类都有一个 Object 作为超类.

Every class has Object as a superclass.

java.lang.Object 类具有方法 toString() 在其中.这意味着您创建的每个类都可以使用该方法,即使它没有被覆盖(它是继承的).当您打印对象时,它会打印该方法的返回值,toString().

举个例子,当你写这个的时候:

So for example, when you write this:

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

和这个一样:

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

您的教师希望您做的是覆盖自动继承的 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.

例如(将此添加到您的 Account 类):

For example (add this to your Account class):

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

通常toString() 方法(如果被覆盖)打印:

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