我已经看到了其他答案,但是在使用多个 try catch 块之后,我的程序在第一个异常处终止。我希望它排除所有四个变量值,然后使用我在每个 catch 块中保留的标志来处理任何异常。
这是我的代码:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Brokerage2 {
public static void main(String[] args) {
float bro = 0, buy = 0, sell = 0;
int quant = 0, flag = 0;
double subtot, pro, bb, bst, sb, ssst, seltot, buytot, surcharge;
Scanner sc = new Scanner(System.in);
try {
bro = sc.nextFloat();
if (bro > 0.03 || bro < 0.0) {
flag = 1;
}
} catch (Exception e) {
flag = 1;
}
try {
buy = sc.nextFloat();
} catch (Exception e) {
flag = 1;
}
try {
sell = sc.nextFloat();
} catch (Exception e) {
flag = 1;
}
try {
quant = sc.nextInt();
} catch (Exception e) {
flag = 1;
}
bb = (buy * quant) * bro * 0.01;
bst = 0.1036 * bb;
buytot = bst + bb;
sb = sell * quant * bro * 0.01;
ssst = sell * quant * 0.00025;
seltot = sb + ssst + bst;
surcharge = ((buy * quant) + (sell * quant)) * 0.00006;
subtot = surcharge + buytot + seltot;
pro = (sell - buy) * quant;
if (flag == 1) {
System.out.println("Invalid Input");
} else if (pro > subtot) {
System.out.println("profit");
System.out.println(Double.parseDouble(new DecimalFormat("##.##").format(pro - subtot)));
} else if (subtot > pro) {
System.out.println("loss");
System.out.println(Double.parseDouble(new DecimalFormat("##.##").format(subtot - pro)));
}
}
}