저는 Java에 익숙하지 않고 중첩되어 있습니다. 3 번 인쇄되는 catch 코드를 사용해보십시오! 왠지 말해줘? 커맨드 라인에서 3 개의 int를 얻었고 유효성을 검사하고 범위 내에 있는지 그리고 try 및 catch를 사용하고 있는지 확인해야합니다. 그러나 대답은 3 번 인쇄됩니다! 당신이 그것을 세 가지 인수의 경우 세 번 실행되는, main()
에 for
루프에 validateInput 메서드 호출을 넣어 이후중첩 된 시도 캐치
// 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;
}
실패한 첫 번째 유효성 검사에 대해 "유효하지 않은 반환"을 원할 수 있습니다. 그렇지 않으면 다른 값으로 계속 시도합니다. 예외 전파가 억제되기 때문에 다른 값을 계속 시도합니다 ([다시] throw없이 catch). 위의 코드를 다시 작성하여 단순화의 첫 번째 단계로 중첩 된 try-catch 블록을 사용하지 않을 것입니다. –
try 및 catch없이 작동하지만 try 및 catch가 필요합니다. ( – NilR
) 중첩 된 try-catch 블록이 필요합니다 (ick!), try * 내부에서 * 후속 논리 * 이동을 고려하십시오. 즉, catch에서 이동하십시오. 예외가 throw되면 후속 코드를 건너 뜁니다 (catch);이 경우에는 후속 코드가 try 내부에 있었기 때문에 최대 하나의 catch를 입력하고 (최대 하나의 메시지 만 출력) –