public class Acc{
private double balance;
public Account()
{
balance = 5;
}
public Acc(double sBalance)
{
balance = sBalance;
}
public void depos(double amount)
{
balance = balance + amount;
}
public void withd(double amount)
{
balance = balance - amount;
if (withd>balance){
System.out.println("Error");
}
}
public double gBalance()
{
return balance;
}
}
主要:
public class Main{
public static void main(String[] args){
Acc newBank = new Acc(50);
newBank.withd(20);
newBank.depos(5);
System.out.println(newBank.gBalance());
}
}
基本上,我想创建一个函数来从余额中提取和存入一个值,在此,向创建的每个新帐户中添加5美元。似乎可行,但是我想扩展并使其提款超过余额,这会导致错误,并且无法从余额中扣除
答案 0 :(得分:1)
首先,您提供的代码不一致,因此无法编译:
public Account()
,而类名是Acc
withd
。应该是amount > balance
。如果我了解您要执行的操作,则撤回方法应为:
public void withd(double amount)
{
if (amount > balance) {
System.out.println("Error");
} else {
balance = balance - amount;
}
}
在执行提款之前,您在其中检查余额是否有足够的钱。