我正在从Deital如何编程第10版进行练习(3.11)我的程序中没有错误但是我希望当提款金额大于平衡时它应该只显示“余额不足”的消息,它不应该显示余额,请帮助我,我只是一个初学者。
这是我的主要计划
package practice;
import java.util.Scanner;
public class apple {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
tuna account1 = new tuna ("James" , 150000);
tuna account2 = new tuna ("David" , 5000);
System.out.printf("%s Balance: %.2f" , account1.getName(),account1.getBalance());
System.out.printf("%n%s Balance: %.2f" , account2.getName(), account2.getBalance());
System.out.print("\nEnter the Ammount that will add in James Account: ");
double depositAmmount = input.nextDouble();
System.out.printf("Adding %.2f to James Account", depositAmmount);
account1.deposit(depositAmmount);
System.out.printf("%n%s Balance: %.2f" , account1.getName(),account1.getBalance());
System.out.print("\nEnter the Ammount that will add in David Account: ");
depositAmmount = input.nextDouble();
System.out.printf("Adding %.2f to David Account", depositAmmount);
account2.deposit(depositAmmount);
System.out.printf("%n%s Balance: %.2f" , account2.getName(),account2.getBalance());
System.out.print("\nEnter the Ammount that will withdrawal from james Account: ");
double wD = input.nextDouble();
System.out.printf("WithDrawal %.2f from James Account",wD);
account1.withDrawal(wD);
System.out.printf("%n%s Balance: %.2f" , account1.getName(),account1.getBalance());
}
}
那就是班级
package practice;
public class tuna {
private String name;
private double balance;
public tuna (String name , double balance){
this.name = name;
if (balance > 0)
this.balance = balance;
}
public void deposit(double depositAmmount){
if (depositAmmount > 0)
balance = balance + depositAmmount;
}
public void withDrawal (double wD){
if (wD > balance)
System.out.println("\nInsufficient Balance");
else
balance = balance - wD;
}
public double getBalance(){
return balance;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
}
答案 0 :(得分:0)
因此,一种可能的解决方案是让函数返回boolean
,指示它是否成功:
public boolean withDrawal (double wD){
if (wD > balance) {
return false;
}
else {
balance = balance - wD;
return true;
}
}
用法:
if(account1.withDrawal(wD)) {
System.out.printf("%n%s Balance: %.2f" , account1.getName(),account1.getBalance());
}
else {
System.out.println("\nInsufficient Balance");
}