gpt4 book ai didi

java - 尝试在 while 循环内 catch block

转载 作者:行者123 更新时间:2023-12-02 04:28:23 25 4
gpt4 key购买 nike

我如何使用 try/catch block ,以便用户可以从他们在程序中出错的地方开始?

while (true) {
try {
System.out.println("Enter your amount paid ");
int payCheck = s.nextInt();
System.out.println("Amount Paid: $" +payCheck);

System.out.println("Enter your expenses");
int expenses = s.nextInt();
System.out.println("Expenses: $" +expenses);

System.out.println("Enter your tax percentage taken off as a decimal:");
float taxRate = s.nextFloat();
System.out.println("Tax Rate" +taxRate);

double totalPay = (double) Math.round(payCheck - expenses)* taxRate ;
DecimalFormat f = new DecimalFormat("##.00");
System.out.println( "Total Pay: $" +f.format(totalPay));
} catch (Exception e) {
System.out.println("Please enter a number");
}
}

最佳答案

使用如下函数:

int readInt(Scanner s) {
int result = 0;
boolean isNumber = false;
while(!isNumber) {
try {
result = s.nextInt();
isNumber = true;
} catch (Exception e) {
System.out.println("Please enter a number");
}
}
return result;
}

并使用如下:

while (true) {
System.out.println("Enter your amount paid ");
int payCheck = readInt(s);
System.out.println("Amount Paid: $" +payCheck);

System.out.println("Enter your expenses");
int expenses = readInt(s);
System.out.println("Expenses: $" +expenses);

System.out.println("Enter your tax percentage taken off as a decimal:");
float taxRate = s.nextFloat(); //Here you must write a function readFloat
System.out.println("Tax Rate" +taxRate);

double totalPay = (double) Math.round(payCheck - expenses)* taxRate ;
DecimalFormat f = new DecimalFormat("##.00");
System.out.println( "Total Pay: $" +f.format(totalPay));
}

关于java - 尝试在 while 循环内 catch block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31846220/

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