我是java的新手,我已经嵌套了3次打印的Try Catch代码!你能告诉我为什么吗? 我从命令行获得3 int并且必须进行验证并检查它们是否在范围内并且我正在使用try和catch。但答案打印3次!
// Global Constants
final static int MIN_NUMBER = 1;
final static int MAX_PRIME = 10000;
final static int MAX_FACTORIAL = 12;
final static int MAX_LEAPYEAR = 4000;
// Global Variable
static int a, b, c;
public static void main(String[] args) {
// String[] myNumbers= new String [3];
// int x =Integer.parseInt(args[0]);
for (int i = 0; i < args.length; i++) {
// System.out.print(args[i]+" ");
validateInput(args[0], args[1], args[2]);
}
}
// Validate User Input
public static boolean validateInput(String value1, String value2, String value3) {
boolean isValid = false;
try {
try {
try {
a = Integer.parseInt(value1);
if (!withinRange(a, MIN_NUMBER, MAX_PRIME)) {
System.out.println(
"The entered value " + value1
+ " is out of range [1 TO 10000].");
}
isValid = true;
} catch (Exception ex) {
System.out.println(
"The entered value " + value1
+ " is not a valid integer. Please try again.");
}
b = Integer.parseInt(value2);
if (!withinRange(b, MIN_NUMBER, MAX_FACTORIAL)) {
System.out.println(
"The entered value " + value2
+ " is out of range [1 TO 12].");
}
isValid = true;
} catch (Exception ex) {
System.out.println(
"The entered value " + value2
+ " is not a valid integer. Please try again.");
}
c = Integer.parseInt(value3);
if (!withinRange(c, MIN_NUMBER, MAX_LEAPYEAR)) {
System.out.println(
"The entered value " + value3
+ " is out of range [1 TO 4000].");
}
isValid = true;
} catch (Exception ex) {
System.out.println(
"The entered value " + value3
+ " is not a valid integer. Please try again.");
}
return isValid;
}
// Check the value within the specified range
private static boolean withinRange(int value, int min, int max) {
boolean isInRange = true;
if (value < min || value > max) {
isInRange = false;
}
return isInRange;
}
答案 0 :(得分:4)
答案打印3次,因为您已将validateInput方法调用放入for
中的main()
循环中,如果有三个参数,则会运行三次。
答案 1 :(得分:2)
我建议编写validateInput
方法来验证单个字符串。为min和max允许的int值添加两个参数。
public static boolean validateInput(String value, int minValue, int maxValue) {
try {
integer intVal = Integer.parseInt(value);
if (intVal < minVal || intVal > maxValue) {
System.out.println("The entered value " + value
+ " is out of range [" + minValue + " TO " + maxValue + "].");
return false;
}
} catch (Exception e) {
System.out.println("The entered value " + value
+ " is not a valid integer. Please try again");
return false;
}
return true;
}