gpt4 book ai didi

java - 当用户为我的自定义异常输入小于 0 的数字时,无法查明问题

转载 作者:行者123 更新时间:2023-12-01 13:10:31 27 4
gpt4 key购买 nike

似乎无法弄清楚这一点。如果用户输入无效余额,我如何重新提示他们再次输入余额并继续我的程序?

  //EDITED STILL WONT WORK PROPERLY
boolean again;
while(again = true)
{
try {

// pass object to printwriter and pw to write to the file
pw = new PrintWriter(fw);

System.out.print("Input beginnning balance: ");
balance = input.nextDouble();
again = false;
// pass user input to object
AccountWithException acctException = new AccountWithException(fullName, balance, id, RATE);
again = false;

System.out.println(acctException.toString());

// copy object to created file
pw.println(acctException.toString());
again = false;

// custom exception
} catch (InvalidBalanceException e) {
System.out.println(e.getMessage());
} catch(FileNotFoundException e) {
System.out.println(e.getMessage());
} finally {
pw.close();

最佳答案

您可以抛出无效余额异常并在catch block 中捕获它,如下所示

try {

// pass object to printwriter and pw to write to the file
pw = new PrintWriter(fw);

// pass user input to object
AccountWithException acctException = new AccountWithException(fullName, balance, id, RATE);

System.out.println(acctException.toString());

// copy object to created file
pw.println(acctException.toString());
throw new InvalidBalanceException ();

// custom exception if balance < 0
} catch (InvalidBalanceException e) {
System.out.println(e.getMessage());
System.out.println("Re-enter balance: ");
balance = input.nextDouble();
} catch(FileNotFoundException e) {
System.out.println(e.getMessage());
} finally {
System.out.println("Text file closed, program complete...");
pw.close();
}

关于java - 当用户为我的自定义异常输入小于 0 的数字时,无法查明问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22903147/

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