我有一个SavingsAccount对象,并且试图使用我的函数来操纵帐户的余额。现在我没有错误但没有输出。我感觉自己做错了什么,我不太了解如何在对象上调用函数。
如果我尝试打印其中一个帐户的输出,则会得到内存地址。
我在进行调整时遇到各种不同的错误,并且最终没有错误。但是仍然没有输出,恐怕我弄错了,它只是个bug,我没有以正确的方式调用我的函数,否则我的构造函数未按照其要求进行编码。
public class SavingsAccount {
// Class
int balance;
int amountToDeposit;
int amountToWithdraw;
//Constructor
public SavingsAccount(int initialBalance, int deposit, int withdraw){
balance = initialBalance;
amountToDeposit = deposit;
amountToWithdraw = withdraw;
}
//Functions thats I wanna call
// Setting balance
public void checkBalance() {
System.out.println("Hello!");
System.out.println("Your balance is " + balance);
}
// Depositing amounts
public void deposit(int amountToDeposit) {
balance = balance + amountToDeposit;
System.out.println("You just deposited" + amountToDeposit);
}
// Withdrawing amounts
public int withdraw(int amountToWithdraw) {
balance = balance - amountToWithdraw;
System.out.println("You just withdrew" + amountToWithdraw);
return amountToWithdraw;
}
// Main
public static void main(String[] args){
//Setting values, balance, deposit, withdraw.
SavingsAccount savings = new SavingsAccount(2000, 100, 2000);
SavingsAccount test = new SavingsAccount(5000, 200, 100);
//Check balance
System.out.println(test); // Will give a memory adress
}
}
我想在我制作的对象上使用我的函数并打印结果。
谢谢阅读。
最佳答案
您好,您可以实现toString
来打印对象,如下所示:
package com.stuart.livealert;
public class SavingsAccount {
// Class
int balance;
int amountToDeposit;
int amountToWithdraw;
//Constructor
public SavingsAccount(int initialBalance, int deposit, int withdraw){
balance = initialBalance;
amountToDeposit = deposit;
amountToWithdraw = withdraw;
}
//Functions thats I wanna call
// Setting balance
public void checkBalance() {
System.out.println("Hello!");
System.out.println("Your balance is " + balance);
}
// Depositing amounts
public void deposit(int amountToDeposit) {
balance = balance + amountToDeposit;
System.out.println("You just deposited" + amountToDeposit);
}
// Withdrawing amounts
public int withdraw(int amountToWithdraw) {
balance = balance - amountToWithdraw;
System.out.println("You just withdrew" + amountToWithdraw);
return amountToWithdraw;
}
@Override
public String toString() {
return "{balance : " + balance + " deposit : " + amountToDeposit + " withdraw : " + amountToWithdraw + " }";
}
// Main
public static void main(String[] args){
//Setting values, balance, deposit, withdraw.
SavingsAccount savings = new SavingsAccount(2000, 100, 2000);
SavingsAccount test = new SavingsAccount(5000, 200, 100);
//Check balance
System.out.println(test); // Will give {balance : 5000 deposit : 200 withdraw : 100 }
}
}