问题
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;
}
回答1:
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);
}
}
Output:
[C:\java_code\]java StringToNumberWithErrLoop
Number please: etuh
etuh is not a number. Try again.
Number please: 2
Number: 2
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);
}
}
Output:
[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
来源:https://stackoverflow.com/questions/22122391/how-do-i-add-exception-handling-for-the-parts-where-the-answer-is-numeric