gpt4 book ai didi

java 捕获数字类型的 NumberFormatException

转载 作者:行者123 更新时间:2023-11-30 06:10:07 25 4
gpt4 key购买 nike

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

我最初尝试在 presentQuestion 方法的开头插入一个 try catch block ,但它给我带来了很多错误。我在实现这些 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;
}
}

}

最佳答案

除了 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;
}

关于java 捕获数字类型的 NumberFormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36427654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com