【问题标题】:java catch a NumberFormatException on a Numeric typejava 在数值类型上捕获 NumberFormatException
【发布时间】:2016-04-05 13:23:16
【问题描述】:

您好,我已经使用 java 创建了一个测验应用程序,但我不确定如何实现这个小部分。它要求我: 如果用户输入字符,即“a”,则添加异常以捕获 NumericQuestion 类型上的 NumberFormatException

我最初尝试在 presentQuestion 方法的开头插入一个 try catch 块,但它给我带来了很多错误。我在实现这些 try-catch 方法方面没有太多经验。我知道它可能很简单,所以任何帮助都将不胜感激。 我的代码如下所示。

package QuestionGame;

import java.util.Scanner;

public class NumericQuestionTester {

    public static void main(String[] args) {
        boolean userCorrect;
        Scanner input = new Scanner(System.in);
        NumericQuestion quThree = new NumericQuestion("What is the answer to 5 divided by 3?", "1.67", 2, 0.03, 0.07);
        presentQuestion(input, quThree);
        input.close();

    }

    public static void presentQuestion(Scanner input, NumericQuestion q) {
        boolean userCorrect;
        q.displayQuestion();
        System.out.println("Enter your answer: ");
        String answer = input.nextLine();
        userCorrect = q.checkAnswer(answer);
        if (userCorrect){
            System.out.println("Correct! The answer is : " + q.getAnswer() + " and you have a score of : " + q.getMark());
        } else {
            System.out.println(answer + " is incorrect. You scored zero.");
        }
        System.out.println();
    }
}


package QuestionGame;

public class NumericQuestion extends Question {

    //instance variables
    private double ansNumeric;
    private double positiveRange;
    private double negativeRange;

    //constructor
    public NumericQuestion(String quText, String answer, int mark, double positiveRange, double negativeRange) {
        super(quText, answer, mark);
        this.ansNumeric = Double.parseDouble(answer);
        this.positiveRange = positiveRange;
        this.negativeRange = negativeRange;
    }

    //accessors & mutators
    public double getAnsNumeric() {
        return ansNumeric;
    }

    public void setAnsNumeric(double ansNumeric) {
        this.ansNumeric = ansNumeric;
    }

    //methods

    public boolean checkAnswer (String answer) {
        double answerDouble = Double.parseDouble(answer);
        if (answerDouble > (this.ansNumeric + this.positiveRange)) {
            return false;
        } else if (answerDouble < (this.ansNumeric - this.negativeRange)) {
            return false;
        } else {
            return true;
        }
    }

}

【问题讨论】:

  • 使用 try/catch 块?
  • 通过this了解java中的异常处理。然后看看你的问题。
  • checkAnswer 是否与 String 参数一起使用?
  • 请显示checkAnswer的代码
  • 编辑了我的答案,我把异常处理和重试逻辑放在一起

标签: java exception numbers format try-catch


【解决方案1】:

除了exception 处理,我建议你添加持久检查,而用户不会输入预期的整数答案。

do{
     System.out.println("You Numeric answer, please")
     String answer = input.nextLine();
}while !answerIsNumeric(answer);
userCorrect = q.checkAnswer(answer);

public boolean answerIsNumeric(String answer){
     try{
         Double.parseDouble(answer);
     }catch(NumberFormatException e){
         return false;
     }
     return true;
} 

【讨论】:

  • 问题要求我向 CATCH 添加一个例外,而不是使用 if 语句
【解决方案2】:

有很多方法可以实现这一点,具体取决于应用程序设计。我会在这里给你看一个 - 如果这不适用,请提供更多细节,虽然我猜这就是你要找的东西

public static void presentQuestion(Scanner input, NumericQuestion q) {
        boolean userCorrect = false;
        boolean isAnswerNumeric = false;
        String answer = null;
        while(! isAnswerNumeric){
            q.displayQuestion();
            System.out.println("Enter your answer (numeric only) : ");
            answer = input.nextLine();
            try{
                Double.parseDouble(answer);
                isAnswerNumeric = true;
            }catch(NumberFormatException nfe){
               // do nothing in this case.. if the number format is correct, 
               // the isAnswerNumeric will be set to true
            }
        }
        userCorrect = q.checkAnswer(answer);
        if (userCorrect){
            System.out.println("Correct! The answer is : " + q.getAnswer() + " and you have a score of : " + q.getMark());
        } else {
            System.out.println(answer + " is incorrect. You scored zero.");
        }
        System.out.println();
}

您可以调整代码以在 catch 块中显示错误消息或您想要执行的任何操作。在这种情况下,作为一个简单的示例,再次询问问题,直到答案为数字

【讨论】:

  • 字符串变量 answer 在 while 循环结束后就在这行代码之前超出范围: userCorrect = q.checkAnswer(answer);关于如何解决这个问题的任何想法?
  • 只是将变量的声明移到了上层范围内。该变量在循环中设置为数值:)
  • 谢谢!工作正常。 NumberFormatException e 是否与 NumberFormatException nfe 做同样的事情?
  • @niilzon,你是偷了我的答案还是我们的想法一致?
  • @Liam :这是您捕获的异常的名称,因此您可以根据需要将其称为“e”。我将 IOExceptions 之类的异常称为“ioe”,FileNotFoundException 称为“fnfe”,将异常称为“e”,但这只是个人阅读约定(我推荐 :))
【解决方案3】:

您可能只需将answer 字符串解析为带有Float.parseFloat 的数字并捕获NumberFormatException

例子:

    String answer = "3.14";

    try {

        float numericAnswer = Float.parseFloat(answer);

        System.out.println("numericAnswer=" + numericAnswer);

    } catch (NumberFormatException e) {

        System.err.println(answer + " is not a number.");
    }

如果通过 添加一个异常来捕获 NumberFormatException - 这作为一个句子没有多大意义 - 他们的意思是 throw 一个异常,只需在 catch 块中添加

throw new WhateverException(answer + " is not a number.");(例如,你可以抛出 RuntimeException)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多