【发布时间】: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