java捕获数值类型上的NumberFormatException
嗨,我已经用java创建了一个测验应用程序,但是我不确定如何实现这个小部分。它要求我: 如果用户输入一个字符,即“a”,则添加一个异常以捕获数字问题类型的NumberFormatException 我最初尝试在presentQuestion方法的开头插入一个try-catch块,但它给我带来了很多错误。我在实现这些try-catch方法方面没有太多经验。我知道这可能很简单,所以任何帮助都将受到感谢。 我的代码如下所示java捕获数值类型上的NumberFormatException,java,exception,numbers,format,try-catch,Java,Exception,Numbers,Format,Try Catch,嗨,我已经用java创建了一个测验应用程序,但是我不确定如何实现这个小部分。它要求我: 如果用户输入一个字符,即“a”,则添加一个异常以捕获数字问题类型的NumberFormatException 我最初尝试在presentQuestion方法的开头插入一个try-catch块,但它给我带来了很多错误。我在实现这些try-catch方法方面没有太多经验。我知道这可能很简单,所以任何帮助都将受到感谢。 我的代码如下所示 package QuestionGame; import java.util
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;
}
}
}
打包游戏;
导入java.util.Scanner;
公共类数字问题测试仪{
公共静态void main(字符串[]args){
布尔用户正确;
扫描仪输入=新扫描仪(System.in);
数字问题qutree=新的数字问题(“5除以3的答案是什么?”,“1.67”,2,0.03,0.07);
当前问题(输入,三问);
input.close();
}
公共静态无效呈现问题(扫描仪输入,数字问题q){
布尔用户正确;
q、 显示问题();
System.out.println(“输入您的答案:”);
字符串answer=input.nextLine();
userCorrect=q.checkAnswer(答案);
if(userCorrect){
System.out.println(“正确!答案是:“+q.getAnswer()+”,你的分数是:“+q.getMark()”);
}否则{
System.out.println(答案+“不正确,您的分数为零”);
}
System.out.println();
}
}
包装问题游戏;
公共类数字问题扩展问题{
//实例变量
私人双代号;
私人双重肯定;
私人双重否定;
//建造师
公共数字问题(字符串quText、字符串答案、整数标记、双正、双负){
超级(文本、答案、标记);
this.ansNumeric=Double.parseDouble(答案);
this.positiveRange=positiveRange;
this.negativeRange=negativeRange;
}
//存取器和变异器
公共双getAnsNumeric(){
返回数字;
}
public void setAnsNumeric(双ansNumeric){
this.ansNumeric=ansNumeric;
}
//方法
公共布尔校验应答(字符串应答){
double answerDouble=double.parseDouble(答案);
if(answerDouble>(this.ansNumeric+this.positiveRange)){
返回false;
}else if(answerDouble<(this.ansNumeric-this.negativeRange)){
返回false;
}否则{
返回true;
}
}
}
您可能只需要使用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(作为一个句子没有多大意义),他们的意思是抛出一个异常,只需添加catch块
抛出新的WhateverException(答案+“不是数字”)代码>(例如,您可以抛出一个运行时异常。根据应用程序的设计,有很多方法可以实现这一点。我会给你看一个在这里-请提供更多的细节,如果这不适用,虽然我猜这是你正在寻找的
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块中执行的任何操作。在这种情况下,作为一个简单的例子,再次询问问题,直到答案是数字除了异常
处理,我建议您添加持久检查,而用户不会输入预期的整数答案
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;
}
使用try/catch block?只需通读一下即可理解java中的异常处理。然后看看你的问题。checkAnswer
是否与String
参数一致?请显示checkAnswer
的代码编辑我的答案,我将异常处理,和retry logic Together该问题要求我添加一个异常以捕获,而不是使用if语句。while循环结束后,字符串变量answer超出范围,就在这行代码之前:userCorrect=q.checkAnswer(answer);关于如何解决这个问题有什么想法吗?只需将变量的声明移到更高的范围内。变量在循环中设置为数值:)谢谢!工作很好。NumberFormatException e是否与NumberFormatException nfe做了相同的事情?@niilzon,你偷了我的答案,还是我们只是朝着同一个方向思考?@Liam:这是你捕获的异常的名称,如果你愿意,可以称它为“e”。我将IOExceptions称为“ioe”,FileNotFoundException称为“fnfe”,exceptions称为“e”,但这只是个人阅读约定(我建议:)