如何为答案为数字的部分添加异常处理? [英] How do i add exception handling for the parts where the answer is numeric?
问题描述
真的很困惑这个。
如何为答案为数字的部分添加异常处理?
不知道在哪里添加try和catch。
Really confused about this. How do i add exception handling for the parts where the answer is numeric? Don't know where to add the try and catch.
do {
//zip code
do {
System.out.println("Enter your zip code(or enter 0 to quit): ");
zip = input.nextInt();
} while ((zip > 99999 || zip < 10000) && zip != 0);
if (zip == 0){
break;
}
//age
do {
System.out.println("Enter your age: ");
age = input.nextInt();
} while (age < 10 || age > 110);
//items
do {
System.out.println("Enter number of items : ");
numItems = input.nextInt();
entries = entries + 1;
if (entries == 3 && numItems < 1) {
System.out.println("Invalid. Order was not counted");
break;
}
推荐答案
循环直到输入有效的号码,是要求一个字符串,尝试将其转换为一个数字,并继续这样做,直到这种转换不失败:
The crude way to loop until a valid number is entered, is to ask for a string, attempt to convert it to a number, and keep doing so until this conversion doesn't fail:
import java.util.Scanner;
/**
<P>{@code java StringToNumberWithTesting}</P>
**/
public class StringToNumberWithTesting {
public static final void main(String[] ignored) {
int num = -1;
do {
nfx2 = null;
System.out.print("Number please: ");
String strInput = (new Scanner(System.in)).next();
try {
num = Integer.parseInt(strInput);
} catch(NumberFormatException nfx) {
nfx2 = nfx;
System.out.println(strInput + " is not a number. Try again.");
}
} while(nfx2 != null);
System.out.println("Number: " + num);
}
}
输出:
[C:\java_code\]java StringToNumberWithErrLoop
Number please: etuh
etuh is not a number. Try again.
Number please: 2
Number: 2
但使用没有例外作为逻辑的替代,在现实世界的应用中永远不是一个好主意。一个更好的方法是确认字符串包含一个数字,您可以使用Commons的 NumberUtils.isNumber(s)
But using the absence of an exception as a substitute for logic is never a good idea in a real-world application. A better way is to confirm the string contains a number, for which you can use Commons' NumberUtils.isNumber(s)
import java.util.Scanner;
import org.apache.commons.lang.math.NumberUtils;
/**
<P>{@code java StringToNumberWithTesting}</P>
**/
public class StringToNumberWithTesting {
public static final void main(String[] ignored) {
int num = -1;
boolean isNum = false;
do {
System.out.print("Number please: ");
String strInput = (new Scanner(System.in)).next();
if(!NumberUtils.isNumber(strInput)) {
System.out.println(strInput + " is not a number. Try again.");
} else {
//Safe to convert
num = Integer.parseInt(strInput);
isNum = true;
}
} while(!isNum);
System.out.println("Number: " + num);
}
}
输出:
[C:\java_code\]java StringToNumberWithTesting
Number please: uthoeut
uthoeut is not a number. Try again.
Number please: 3
Number: 3
有些更多信息: >
Some more information: How to check if a String is numeric in Java
这篇关于如何为答案为数字的部分添加异常处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!