Java 中的 try/catch

发布于 2024-08-17 17:57:35 字数 2259 浏览 6 评论 0原文

有人可以给我提示为什么这个尝试和捕获不起作用吗? 它抛出扫描仪异常,而不是打印我期望的消息。

import java.util.*;
import java.io.*;
import java.math.*;
import javax.swing.*;

public class Main {
    public static void main(String[] args) {
        Boolean test = true;
        while (test == true) {
            try {
                double x, y;
                String operator;
                Scanner scan = new Scanner(System.in);
                Scanner scan_2 = new Scanner(System.in);
                Scanner ScanOperator = new Scanner(System.in);
                System.out.println(" Enter a double value: ");
                x = scan.nextDouble();
                System.out.println(" Enter another double value: ");
                y = scan_2.nextDouble();
                System.out.println(" Enter a operator for the operation you want to execute, or X if you want to quit: ");
                operator = ScanOperator.nextLine();
                if (operator.equals("x") || operator.equals("X")) {
                    test = false;
                    System.out.println("No calculation was made!!!");
                }
                System.out.println(Calculation(operator, x, y));
            } catch (NumberFormatException nfe) {
               JOptionPane.showMessageDialog(null,"Input must be a number.");
            }
        }
    }

    public static double Calculation(String operator, double x, double y) {
        double result = 0;
        double myAdd = 0;
        double mySub = 0;
        double myMult = 0;
        double myDiv = 0;
        double myPower = 0;
        double myMod = 0;

        if (operator.equals("+")) {
            myAdd = x + y;
            result = myAdd;
        } else if (operator.equals("-")) {
            mySub = x - y;
            result = mySub;
        } else if (operator.equals("*")) {
            myMult = x * y;
            result = myMult;
        } else if (operator.equals("/")) {
            myDiv = x / y;
            result = myDiv;
        } else if (operator.equals("^")) {
            myPower = Math.pow(x, y);
            result = myPower;
        } else if (operator.equals("%")) {
            myMod = x % y;
            result = myMod;
        } else {
        }

        return result;
    }
}

Could someone please give me a hint why this try and catch is not working?
It throws a scanner exception instead of printing the message I expect.

import java.util.*;
import java.io.*;
import java.math.*;
import javax.swing.*;

public class Main {
    public static void main(String[] args) {
        Boolean test = true;
        while (test == true) {
            try {
                double x, y;
                String operator;
                Scanner scan = new Scanner(System.in);
                Scanner scan_2 = new Scanner(System.in);
                Scanner ScanOperator = new Scanner(System.in);
                System.out.println(" Enter a double value: ");
                x = scan.nextDouble();
                System.out.println(" Enter another double value: ");
                y = scan_2.nextDouble();
                System.out.println(" Enter a operator for the operation you want to execute, or X if you want to quit: ");
                operator = ScanOperator.nextLine();
                if (operator.equals("x") || operator.equals("X")) {
                    test = false;
                    System.out.println("No calculation was made!!!");
                }
                System.out.println(Calculation(operator, x, y));
            } catch (NumberFormatException nfe) {
               JOptionPane.showMessageDialog(null,"Input must be a number.");
            }
        }
    }

    public static double Calculation(String operator, double x, double y) {
        double result = 0;
        double myAdd = 0;
        double mySub = 0;
        double myMult = 0;
        double myDiv = 0;
        double myPower = 0;
        double myMod = 0;

        if (operator.equals("+")) {
            myAdd = x + y;
            result = myAdd;
        } else if (operator.equals("-")) {
            mySub = x - y;
            result = mySub;
        } else if (operator.equals("*")) {
            myMult = x * y;
            result = myMult;
        } else if (operator.equals("/")) {
            myDiv = x / y;
            result = myDiv;
        } else if (operator.equals("^")) {
            myPower = Math.pow(x, y);
            result = myPower;
        } else if (operator.equals("%")) {
            myMod = x % y;
            result = myMod;
        } else {
        }

        return result;
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

牵强ㄟ 2024-08-24 17:57:36

很简单,程序抛出了ScannerException,但是你的try catch只能捕获NumberFormatException,你需要添加另一个catch子句才能捕获ScannerException,或者只捕获通用的Exception。

例如,当您说:

 } catch (NumberFormatException nfe) {     
     JOptionPane.showMessageDialog(null,"Input must be a number.");
 }

那只是指定如何捕获 NumberFormatException。
为了捕获所有异常,您需要这样做:

 } catch (NumberFormatException nfe) {     
     JOptionPane.showMessageDialog(null,"Input must be a number.");
 }catch (Exception e){
     JOptionPane.showMessageDialog(null,"Generic exception caught");
 }

在这种情况下,第二个 catch 将获取第一个 catch 中未捕获的所有内容,因为所有异常都扩展了 Exception 类,您可以使用该语句捕获所有派生类。

但是,由于捕获异常本身是不受欢迎的,因此您也可以这样做:

 } catch (NumberFormatException, ScannerException e) {     
     JOptionPane.showMessageDialog(null,"Input must be a number.");
 }

在同一块中捕获两个异常。

Simple, the program throws ScannerException, but your try catch can only catch NumberFormatException, you need to add another catch clause in order to catch ScannerException, or catch only the generic Exception.

for example, when you say:

 } catch (NumberFormatException nfe) {     
     JOptionPane.showMessageDialog(null,"Input must be a number.");
 }

that is only specifying how to catch NumberFormatException.
In order to catch all exceptions, you would need to make it:

 } catch (NumberFormatException nfe) {     
     JOptionPane.showMessageDialog(null,"Input must be a number.");
 }catch (Exception e){
     JOptionPane.showMessageDialog(null,"Generic exception caught");
 }

In this case, the second catch would get everything that was not caught in the first catch because all exceptions extend the Exception class, you can catch all derived classes with that statement.

However, since catching Exception by itself is frowned upon, you could also do:

 } catch (NumberFormatException, ScannerException e) {     
     JOptionPane.showMessageDialog(null,"Input must be a number.");
 }

To catch both exceptions in the same block.

感情废物 2024-08-24 17:57:36

您正在尝试捕获 NumberFormatException。您需要为 ScannerException 添加 catch 语句,因为它与 NumberFormatException 不同。

You're attempting to catch a NumberFormatException. You need to add a catch statement for a ScannerException, as it is different from a NumberFormatException.

不必了 2024-08-24 17:57:36

您需要捕获 ScannerException 或类似的异常。

在此代码中,您仅捕获 NumberFormatException

尝试一些这样的:

    try {
       ...
    } catch (NumberFormatException, ScannerException exception) {
       JOptionPane.showMessageDialog(null,"Input must be a number.");
    }

You need to catch a ScannerException or some like this.

At this code you are only catching the NumberFormatException .

Try some like this:

    try {
       ...
    } catch (NumberFormatException, ScannerException exception) {
       JOptionPane.showMessageDialog(null,"Input must be a number.");
    }
画尸师 2024-08-24 17:57:36

您捕获了错误的异常。

You're catching the wrong exception.

转身泪倾城 2024-08-24 17:57:36

您的代码不会抛出 NumberFormatException。您应该改为捕获 InputMismatchException

查看 nextDouble,在 Scanner 中,似乎 Scanner 代码为您处理 NumberFormatException,然后抛出一个不同类型的异常:

来自 java.util.Scanner

public double nextDouble() {
    // Check cached result
    if ((typeCache != null) && (typeCache instanceof Double)) {
        double val = ((Double)typeCache).doubleValue();
        useTypeCache();
        return val;
    }
    setRadix(10);
    clearCaches();
    // Search for next float
    try {
        return Double.parseDouble(processFloatToken(next(floatPattern())));
    } catch (NumberFormatException nfe) {
        position = matcher.start(); // don't skip bad token
        throw new InputMismatchException(nfe.getMessage());
    }
} 

当您遇到这样的问题时,我建议您首先查看 Java 源代码。这是一个很好的资源。

另请注意,JDK 中没有 ScannerException

Your code will not throw a NumberFormatException. You should catch an InputMismatchException instead.

Looking at nextDouble, in Scanner, it seems that the Scanner code handles the NumberFormatException for you and then throws a different type of exception:

from java.util.Scanner:

public double nextDouble() {
    // Check cached result
    if ((typeCache != null) && (typeCache instanceof Double)) {
        double val = ((Double)typeCache).doubleValue();
        useTypeCache();
        return val;
    }
    setRadix(10);
    clearCaches();
    // Search for next float
    try {
        return Double.parseDouble(processFloatToken(next(floatPattern())));
    } catch (NumberFormatException nfe) {
        position = matcher.start(); // don't skip bad token
        throw new InputMismatchException(nfe.getMessage());
    }
} 

When you hit a problem like this, I recommend that you look through the Java source as a first stop. It is a great resource.

Also note that there is no ScannerException in the JDK.

海之角 2024-08-24 17:57:36

只需捕获 InputMismatchException 而不是 NumberFormatException 即可,一切正常。

Just catch InputMismatchException instead of NumberFormatException and everything works fine.

吹梦到西洲 2024-08-24 17:57:36

为什么不这样做:

String input = scan.nextLine();
if(!input.matches("\\d+")) { // regex for 1 or more digits
    System.err.println("Input must be at least 1 digit!");
    continue; // goes back to the top of the loop
}
double dbl = Double.valueOf(input);

仅供参考,双精度的实际正则表达式将是 [digit][.][digit],其中 [.][digit] 是可选的。

Why not just do:

String input = scan.nextLine();
if(!input.matches("\\d+")) { // regex for 1 or more digits
    System.err.println("Input must be at least 1 digit!");
    continue; // goes back to the top of the loop
}
double dbl = Double.valueOf(input);

FYI, the actual regex for double precision would be [digit][.][digit] with the [.][digit] being optional.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文