gpt4 book ai didi

java - 创建用户定义的异常类-获取 null 作为答案(JAVA)

转载 作者:行者123 更新时间:2023-12-01 06:34:43 24 4
gpt4 key购买 nike

我尝试实现以下问题,但在尝试将值传递给方法时得到 null 作为答案。提现时计算新余额后,我似乎无法将值传递给方法transfer。

enter image description here

帐户类别:

package Number3;

public class Account {

private int balance;
private int maxTransfer;

public Account()
{
balance = 0;
maxTransfer = 0;
}

public Account(int bal,int maxT)
{
balance = bal;
maxTransfer = maxT;
}

public void setBalance(int b)
{
balance = b;
}

public int getBalance()
{
return balance;
}

public void setMaxTransfer(int m)
{
this.maxTransfer = m;
}

public int getMaxTransfer()
{
return maxTransfer;
}

public void withdraw(int amount) throws insufficientFundException
{
if(!(amount < balance))
{
balance = balance - amount;
}
else
{
throw new insufficientFundException();
}
}

public void transfer(int amount)
{
balance = amount + balance;
}

public void display()
{
System.out.println("Current balance: "+getBalance());
}
}

testAccount 主要:

package Number3;
import java.util.Scanner;

public class testAccount{

public static void main(String[] args) {

try{
Account a = new Account();
a.setBalance(1000);
a.setMaxTransfer(10000);
int choice,amount,acc;

Scanner input = new Scanner(System.in);

a.display();

System.out.println("1. Withdraw \t\t 2. Transfer");
System.out.println("Choose either 1 or 2");
choice = input.nextInt();

switch(choice)
{
case 1:
{
System.out.println("Enter amount to withdraw: ");
amount = input.nextInt();
a.withdraw(amount); //where i assume the error is
a.getBalance();
break;
}
case 2:
{
System.out.println("Enter amount to transfer: ");
amount = input.nextInt();
a.transfer(amount);
a.getBalance();
break;
}
default:
{
System.out.print("Enter 1 or 2: ");
choice = input.nextInt();
}
}


}
catch(insufficientFundException ife)
{
System.out.print(ife.getMessage());
}

}
}

以及用户定义的异常的类:

package Number3;

public class insufficientFundException extends Exception{

public static void main(String[] args) {
System.out.println("You don't have enough funds in your account.");

}

}

请告诉我我做错了什么。谢谢。

最佳答案

这个 main 方法永远不会被调用。将异常添加到构造函数中的父类(super class)

package Number3;

public class insufficientFundException extends Exception{

insufficientFundException(String msg){
super(msg);
}

}

在您的代码中发生此异常时抛出

if(balance-withdrawal<0){
throw new insufficientFundException("Your error message");
}

关于java - 创建用户定义的异常类-获取 null 作为答案(JAVA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28797772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com