为什么这个try语句使用catch语句?

ymzxtsji  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(372)

**结束。**此问题需要详细的调试信息。它目前不接受答案。
**想改进这个问题吗?**更新问题,使其成为堆栈溢出的主题。

上个月关门了。
改进这个问题

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的第一部分,我告诉它print subtract,但它却调用catch语句。有人能帮忙吗?请记住,我是一个初学者在编码。

hujrc8aj

hujrc8aj1#

你已经宣布 subtract 以及 amounttaken 作为 boolean 变量,因此它们只能 true 或者 false 因为下面给出的值是一个示例运行:

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

如果尝试输入不同于 true 或者 false ,你会得到 InputMismatchException .
我想您应该为变量输入一些十进制数(amount), amounttaken . 如果是,声明为 double 或者 float 而不是 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
dly7yett

dly7yett2#

它是一个完整的结构。

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

如果try块中的代码可能引发异常,则可以执行另一种方法。就像上面的代码一样,如果任何人输入一个字符串而不是布尔值,它将抛出inputmismatchexception,它将被捕获在catch块中,您可以将错误消息打印到用户nice and clearly.:)

相关问题