如何在银行程序中打印余额 (Java)

huangapple go评论115阅读模式
英文:

How to print balance in a banking program (Java)

问题

我已经创建了一个用于银行业务的Java程序,允许用户存款、取款并查看余额。

然而,我希望能够在调用getBalance()命令时打印convToString数据(nameaccNobalance)。这比每次想要打印账户信息时都要输入`System.out.println(JohnSmith.convToString()+"\n")``要高效得多。

关于如何优化代码并实现这一点,有什么建议吗?

以下是完整的源代码...

package week1src;

public class BankAccount {
    
    private String name;
    private int accNo;  
    private double balance;
    
    
    // Constructor to initialise all 3 instance variables
    public BankAccount(String n, int a, double amount)
    {    
        name = n;
        accNo = a;
        balance = amount;
    }
    
    // Constructor to set default opening account balance to zero
    public BankAccount(String n, int a)
    {
        name = n;
        accNo = a;
        balance = 0.00;
    }
    
    
    /* --------------------
       返回一个包含基于账户名输入的所有账户信息的字符串
       --------------------*/
    public String convToString(  ) 
    {
        return("Account name: " + this.name + ", Account number: " + this.accNo + ", Available balance: " + "£" + this.balance);
    }
    
    
    /* --------------------
       存款方法,将“amount”添加到余额中
       --------------------*/
    public void deposit(double amount) {
        if (amount <= 0) { 
            // 如果输入的值为负数,返回错误消息
            System.err.println("Cannot deposit negative amounts. Please enter a different amount.");
        }
        else {
            this.balance += amount;
            System.out.format("£%.2f has been deposited\n", amount);
        }
    }
    
    
    /* --------------------
       取款方法,从余额中减去“amount”
       --------------------*/
    public void withdraw(double amount) {
        if (this.balance >= amount) { 
            this.balance -= amount;
            System.out.format("£%.2f has been withdrawn\n", amount);
        }
        else { // 如果取款后账户余额小于0,则返回错误消息
            System.err.println("Transaction cancelled due to insufficient funds. Check balance or deposit funds.");
        }
    }
    
    
    /* --------------------
       用于显示账户余额的方法
       --------------------*/
    public double getBalance() {
        return balance;
        // 每当调用getBalance()时,我想打印convToString信息。
    }
}
package week1src;

public class BankMain {

    public static void main(String[] args) {
        
        BankAccount JohnSmith = new BankAccount("John Smith", 1, 00);    // 创建一个账户对象(账户名、账号、开户余额)
        //BankAccount DavidJones = new BankAccount("David Jones", 2, 1000);    // 创建一个账户对象(账户名、账号、开户余额)
                
        System.out.println(JohnSmith.convToString()+"\n"); // 将显示账户名、账号和当前余额(£0)
        JohnSmith.deposit(100); // 存款£100              
        JohnSmith.deposit(-50); // 由于负值而返回错误
        JohnSmith.deposit(10);    // 存款£10
        JohnSmith.withdraw(25); // 取款£25
        JohnSmith.withdraw(90); // 由于余额将小于0,返回错误
        System.out.println(JohnSmith.getBalance()); // 显示余额
        JohnSmith.withdraw(70); // 取款£70       
        System.out.println(JohnSmith.convToString()+"\n"); // 将显示账户名、账号和当前余额(£15.00)
    }
}
英文:

I have created a Java program for banking, which allows the user to deposit funds, withdraw funds, and check their balance.

However, I would like to be able to print the convToString data (name, accNo, balance) whenever the getBalance() command is called. This would be much more effective than having to type System.out.println(JohnSmith.convToString()+&quot;\n&quot;) each time I want to print the account information.

Any advice on how best to clean my code up and make this happen?

My full source code follows...

package week1src;
public class BankAccount {
private String name;
private int accNo;	
private double balance;
// Constructor to initialise all 3 instance variables
public BankAccount(String n, int a, double amount)
{	
name = n;
accNo = a;
balance = amount;
}
// Constructor to set default opening account balance to zero
public BankAccount(String n, int a)
{
name = n;
accNo = a;
balance = 0.00;
}
/* --------------------
Return a String containing all the information of the account based on account name input
--------------------*/
public String convToString(  ) 
{
return(&quot;Account name: &quot; + this.name + &quot;, Account number: &quot; + this.accNo + &quot;, Available balance: &quot; + &quot;&#163;&quot; + this.balance);
}
/* --------------------
Method to deposit funds by adding &quot;amount&quot; to balance 
--------------------*/
public void deposit(double amount) {
if (amount &lt;= 0) { 
// returns an error message is value entered is negative
System.err.println(&quot;Cannot deposit negative amounts. Please enter a different amount.&quot;);
}
else {
this.balance += amount;
System.out.format(&quot;&#163;%.2f has been deposited\n&quot;, amount);
}
}
/* --------------------
Method to withdraw funds by subtracting &quot;amount&quot; from balance 
--------------------*/
public void withdraw(double amount) {
if (this.balance &gt;= amount) { 
this.balance -= amount;
System.out.format(&quot;&#163;%.2f has been withdrawn\n&quot;, amount);
}
else { // returns an error message if withdrawal with put account balance below 0
System.err.println(&quot;Transaction cancelled due to insufficient funds. Check balance or deposit funds.&quot;);
}
}
/* --------------------
Method used to display account balance 
--------------------*/
public double getBalance() {
return balance;
// i want to print the convToString info whenever getBalance() is called.
}
}

package week1src;
public class BankMain {
public static void main(String[] args) {
BankAccount JohnSmith = new BankAccount(&quot;John Smith&quot;, 1, 00); 	// create an account object (acc name, acc no, opening balance)
//BankAccount DavidJones = new BankAccount(&quot;David Jones&quot;, 2, 1000); 	// create an account object (acc name, acc no, opening balance)
System.out.println(JohnSmith.convToString()+&quot;\n&quot;); // will display acc name, acc number, and current balance (&#163;0)
JohnSmith.deposit(100); // deposit &#163;100				
JohnSmith.deposit(-50); // will return error due to negative value
JohnSmith.deposit(10);	// deposit &#163;10
JohnSmith.withdraw(25); // withdraw &#163;25
JohnSmith.withdraw(90); // will return error as balance will go &lt;0
System.out.println(JohnSmith.getBalance()); // display balance
JohnSmith.withdraw(70); // withdraw &#163;70		
System.out.println(JohnSmith.convToString()+&quot;\n&quot;); // will display acc name, acc number, and current balance (&#163;15.00)
}
}

答案1

得分: 0

这样可以实现:

BankAccount.java:

public class BankAccount {

  private String name;
  private int accNo;
  private double balance;

  // 用于初始化所有三个实例变量的构造函数
  public BankAccount(String n, int a, double amount) {
    name = n;
    accNo = a;
    balance = amount;
  }

  // 用于将默认的开户余额设置为零的构造函数
  public BankAccount(String n, int a) {
    name = n;
    accNo = a;
    balance = 0.00;
  }

  // 存款方法,通过将“amount”添加到余额中来存款
  public void deposit(double amount) {
    if (amount <= 0) {
      // 如果输入值为负数,则返回错误消息
      System.err.println("不能存入负金额。请输入其他金额。");
    } else {
      this.balance += amount;
      System.out.format("已存入 £%.2f\n", amount);
    }
  }

  // 取款方法,通过从余额中减去“amount”来取款
  public void withdraw(double amount) {
    if (this.balance >= amount) {
      this.balance -= amount;
      System.out.format("已取出 £%.2f\n", amount);
    } else {
      // 如果取款将账户余额降至0以下,则返回错误消息
      System.err.println("由于余额不足,交易已取消。请检查余额或存入资金。");
    }
  }

  // 用于显示账户余额的方法
  public double getBalance() {
    return balance;
    // 每次调用getBalance()时,我想打印convToString信息。
  }

  public void printAccountInfo() {
    System.out.println(this);
  }

  @Override
  public String toString() {
    return "账户名:" + this.name + ",账户号码:" + this.accNo
        + ",可用余额:" + "£" + this.balance;
  }
}

BankMain.java:

package your.package.here;

public class BankMain {

  public static void main(String[] args) {

    BankAccount JohnSmith = new BankAccount("John Smith", 1,
        0);   // 创建一个账户对象(账户名、账户号码、开户余额)
    //BankAccount DavidJones = new BankAccount("David Jones", 2, 1000);     // 创建一个账户对象(账户名、账户号码、开户余额)

    JohnSmith.printAccountInfo();
    JohnSmith.deposit(100); // 存入 £100
    JohnSmith.deposit(-50); // 由于为负数,将返回错误
    JohnSmith.deposit(10);  // 存入 £10
    JohnSmith.withdraw(25); // 取出 £25
    JohnSmith.withdraw(90); // 由于余额将小于0,将返回错误
    System.out.println(JohnSmith.getBalance()); // 显示余额
    JohnSmith.withdraw(70); // 取出 £70
    JohnSmith.printAccountInfo();
  }
}

似乎合理的做法是创建一个单独的可重用打印方法,该方法将完成您所需的所有操作。而不是创建convToString方法,您可以只是重写toString方法,然后按照我发布的方式使用它。这是内置的Java机制,正好可以满足您的需求。

这里的关键是,当您调用System.out.println(this);时,默认行为是在您传递给System.out.println方法的对象上调用toString方法。

这里的神奇之处在于,您只需重写toString,然后在对象实例上调用System.out.println。然后它会获取您的实例,并在该实例上调用您重写的toString方法。

请参考一下。

英文:

It can be achieved like this:

BankAccount.java:

public class BankAccount {
private String name;
private int accNo;
private double balance;
// Constructor to initialise all 3 instance variables
public BankAccount(String n, int a, double amount) {
name = n;
accNo = a;
balance = amount;
}
// Constructor to set default opening account balance to zero
public BankAccount(String n, int a) {
name = n;
accNo = a;
balance = 0.00;
}
/* --------------------
Method to deposit funds by adding &quot;amount&quot; to balance
--------------------*/
public void deposit(double amount) {
if (amount &lt;= 0) {
// returns an error message is value entered is negative
System.err.println(&quot;Cannot deposit negative amounts. Please enter a different amount.&quot;);
} else {
this.balance += amount;
System.out.format(&quot;&#163;%.2f has been deposited\n&quot;, amount);
}
}
/* --------------------
Method to withdraw funds by subtracting &quot;amount&quot; from balance
--------------------*/
public void withdraw(double amount) {
if (this.balance &gt;= amount) {
this.balance -= amount;
System.out.format(&quot;&#163;%.2f has been withdrawn\n&quot;, amount);
} else { // returns an error message if withdrawal with put account balance below 0
System.err.println(
&quot;Transaction cancelled due to insufficient funds. Check balance or deposit funds.&quot;);
}
}
/* --------------------
Method used to display account balance
--------------------*/
public double getBalance() {
return balance;
// i want to print the convToString info whenever getBalance() is called.
}
public void printAccountInfo() {
System.out.println(this);
}
@Override
public String toString() {
return &quot;Account name: &quot; + this.name + &quot;, Account number: &quot; + this.accNo
+ &quot;, Available balance: &quot; + &quot;&#163;&quot; + this.balance;
}
}

BankMain.java:

package your.package.here;
public class BankMain{
public static void main(String[] args) {
BankAccount JohnSmith = new BankAccount(&quot;John Smith&quot;, 1,
0);   // create an account object (acc name, acc no, opening balance)
//BankAccount DavidJones = new BankAccount(&quot;David Jones&quot;, 2, 1000);     // create an account object (acc name, acc no, opening balance)
JohnSmith.printAccountInfo();
JohnSmith.deposit(100); // deposit &#163;100
JohnSmith.deposit(-50); // will return error due to negative value
JohnSmith.deposit(10);  // deposit &#163;10
JohnSmith.withdraw(25); // withdraw &#163;25
JohnSmith.withdraw(90); // will return error as balance will go &lt;0
System.out.println(JohnSmith.getBalance()); // display balance
JohnSmith.withdraw(70); // withdraw &#163;70
JohnSmith.printAccountInfo();
}
}

It seems reasonable to create a separate reusable printing method, that will do all what you need. And instead of creating your convToString method, you can just override toString and then use it in a way that I've posted. This is built in java mechanism that do exactly what you need.

Tricky thing here is when you're calling System.out.println(this); default behavior is to call toString method on that object that you've passed to the System.out.println method.

And here is the magic happens, you just override toString, and then call System.out.println on your object instance. It will then take your instance and call your overrided toString on that.

Please, have a look.

huangapple
  • 本文由 发表于 2020年10月12日 19:38:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64317149.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定