如何创建检查int范围,数字类型而不是char的异常? [英] How can I create an exception that checks for int range, number type, and not a char?
问题描述
我正试图绕过异常,我遇到的问题是我需要创建一个程序,要求用户输入数字9-99。必须使用3个不同的例外对此数字进行错误检查。
I'm trying to wrap my head around exceptions and the problem I'm running into is that I'm being required to create a program that asks for user input for a number 9-99. This number must be error-checked using 3 different exceptions.
e1:数字超出范围(200)
e1: number is outside of the range (200)
e2:number是整数以外的数据类型(double)
e2: number is of a data type other than integer (double)
e3:输入是数字以外的其他数据类型( char)
e3: input is another data type other than number (char)
我试图在我的if结构中创建模式以使所有三个工作,但是我无法区分它在e2和e3之间。它将始终默认为e2。这是我所拥有的只有两个例外,但我非常感谢帮助找出如何实现第三个。谢谢。
I have tried to create patterns in my if structure to make all three work, however I can't get it to differentiate between e2 and e3. It will always default to e2. This is what I have with only two exceptions, but I would greatly appreciate help with figuring out how to implement the third. Thank you.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean tryAgain = true;
do {
try {
System.out.println("Please enter an integer between 9 and 99: ");
int inInt = input.nextInt();
if (inInt >= 9 && inInt <= 99){
System.out.println("Thank you. Initialization completed.");
tryAgain = false;
}
else if (inInt < 9 || inInt > 99){
throw new NumberFormatException("Integer is out of range.");
}
}
catch (NumberFormatException e1) { // Range check
System.out.println("* The number you entered is not between 9 and 99. Try again.");
System.out.println();
input.nextLine();
}
catch (InputMismatchException e2) { // Something other than a number
System.out.println("* You did not enter an integer. Try again.");
System.out.println();
input.nextLine();
}
} while(tryAgain);
}
}
这是我现在得到的输出:
Here is the output I get right now:
请输入9到99之间的整数:
2
Please enter an integer between 9 and 99: 2
- 您输入的数字不在9到99之间。请重试。
请输入9到99之间的整数:
f
Please enter an integer between 9 and 99: f
- 您没有输入整数。再试一次。
请输入9到99之间的整数:
88
Please enter an integer between 9 and 99: 88
谢谢。初始化完成。
推荐答案
如果你必须检测三种情况,你需要有三组逻辑。
If you've got to detect three circumstances, you need to have three sets of logic.
- 检查输入的字符是否是有效的数值。
- 检查输入的数字是否为整数。
- 检查输入的数字是否介于低限和高限之间。
你几乎必须按顺序检查它们。
And you pretty much have to check them in that order.
扫描仪方便地拥有 hasXXX
查看要读取的字符是否与给定模式匹配的方法。
Scanner conveniently has the hasXXX
methods to see whether the characters about to be read match a given pattern.
这篇关于如何创建检查int范围,数字类型而不是char的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!