为什么这个try语句要用到catch语句呢?

Why does this try statement use the catch statement?

import java.util.Scanner;
import java.util.InputMismatchException;
public class bank {
    public static void login() {
        double balance;
        try {
            boolean subtract;
            boolean amounttaken;
            // This is to see if you want to withdraw money
            System.out.println("Do you want to withdraw money?");
            Scanner SCaddOrWithdraw = new Scanner(System.in);
            subtract = SCaddOrWithdraw.nextBoolean();
            if (subtract) {
                System.out.println("How much would you like to withdraw?");
                Scanner SCamounttaken = new Scanner(System.in);
                amounttaken = SCamounttaken.nextBoolean();
                System.out.println("Subtract");
            } else if (!subtract) {
                System.out.print("Ask for bal");
            }
        } catch (InputMismatchException e) {
            System.out.println("Invalid Input");
        }
    }
}

我添加了一个 try 语句,在 if 的第一部分我告诉它打印 subtract 但它调用了赶上语句。有人可以帮忙吗? 请记住,我是编码初学者。

结构完整

try {
    // Statement Which May Throw Exceptions
} catch(Exception e) {
    // If any statement throws the exception
    // Do alternative flow here
}

如果您在 try 块中的代码可能会抛出异常,您可以采用替代方法。就像在上面的代码中一样,如果有人输入字符串而不是布尔值,它将抛出 InputMismatchException,这将在 catch 块中捕获,您可以将错误消息漂亮而整洁地打印给用户。 :)

您已将 subtractamounttaken 声明为 boolean 变量,因此它们只能采用 truefalse 作为值,例如下面给出了一个示例 运行:

Do you want to withdraw money?
true
How much would you like to withdraw?
true
Subtract

如果您尝试输入不同于 truefalse 的值,您将得到 InputMismatchException

我想你想为变量输入一些小数(数量),amounttaken。如果是,请将其声明为 doublefloat 而不是 boolean 例如

import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        login();
    }

    public static void login() {
        double balance;
        try {
            boolean subtract;
            double amounttaken;// Changed to double
            // This is to see if you want to withdraw money
            System.out.println("Do you want to withdraw money?");
            Scanner SCaddOrWithdraw = new Scanner(System.in);
            subtract = SCaddOrWithdraw.nextBoolean();
            if (subtract) {
                System.out.println("How much would you like to withdraw?");
                Scanner SCamounttaken = new Scanner(System.in);
                amounttaken = SCamounttaken.nextDouble();// Changed for double
                System.out.println("Subtract");
            } else if (!subtract) {
                System.out.print("Ask for bal");
            }
        } catch (InputMismatchException e) {
            System.out.println("Invalid Input");
        }
    }
}

样本运行:

Do you want to withdraw money?
true
How much would you like to withdraw?
3000
Subtract