사용자에게 값을 입력하라는 메서드를 구현했습니다. 해당 값이 범위를 벗어 났거나 올바른 값 유형이 아닌 경우 오류 메시지가 표시되고 다시 묻습니다.스캐너를 사용하여 올바른 입력 값 얻기
public static Integer getValue (Integer minValue, Integer maxValue) {
Scanner input;
input = new Scanner (System.in);
Integer value;
value = null;
while (true) {
try {
value = input.nextInt();
input.nextLine();
if ((value >= minValue) && (value <= maxValue)) {
break;
} else {
// Shows message that says value is not in range.
continue;
}
} catch (InputMismatchException IME) {
// Shows message that says value is not an integer.
input.next();
continue;
}
}
input.close();
return(value);
}
원하지 않는 값이 지정되면 코드를 올바르게 식별 할 수 있습니다. 이 문제는 값이 실제로 올바른 경우에 발생하며 디버거로 전달됩니다.
이
은 실행의 예입니다 여기Select the type of furniture:
1. - Dresser.
2. - Shelf.
3. - Rectangular table.
4. - Round table.
You chose: abc // Asks again because the value entered is not int.
a b c
adsf
5 // Asks again because the value entered is not in range.
1 // Here it is when the compiler takes me to the debugger.
내가이 시점 과거의 실행을 강제하는 경우 발생하는 상황; 그것은 다른 값에 대한 사용자 요청 후 나에게 다음 완전히 충돌 아래의 메뉴를 보여줍니다
furnitureMenu();
indexTree = getValue(minIndexFurniture, maxIndexFurniture);
woodMenu();
indexWood = getValue(minIndexWood, maxIndexWood);
그것은 내가 일을이 방법을 얻을 결정적 :
Select the type of wood.
1. - Mahogamy.
2. - Cherry-tree.
3. - Walnut.
4. - Pine tree.
5. - Oak tree.
You chose: Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
이것은 메인에서 호출되는 어떻게입니다 왜냐하면 위에서 보았 듯이 메뉴에서 선택하는 것뿐만 아니라 치수와 같은 가구 사양을 얻고 싶지 않기 때문에 사용자가 여러 번 입력해야하기 때문입니다.
모든 도움을 주실 수 있습니다. 미리 감사드립니다.
내 컴퓨터에서이 기능을 실행하는 데 문제가 없습니다. –
@FallaCoulibaly 당신은 당신의 메인 내부에서 그것을 두 번째로 호출 할 수 있고, 그것이 나를 위해했던 것처럼 멈추거나 충돌하는지 볼 수 있습니까? – ShadowGeist
나는 이것을'Integer indexTree = getValue (0, 4);와 같이 main에서 호출했다. –