0

사용자에게 값을 입력하라는 메서드를 구현했습니다. 해당 값이 범위를 벗어 났거나 올바른 값 유형이 아닌 경우 오류 메시지가 표시되고 다시 묻습니다.스캐너를 사용하여 올바른 입력 값 얻기

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) 

이것은 메인에서 호출되는 어떻게입니다 왜냐하면 위에서 보았 듯이 메뉴에서 선택하는 것뿐만 아니라 치수와 같은 가구 사양을 얻고 싶지 않기 때문에 사용자가 여러 번 입력해야하기 때문입니다.

모든 도움을 주실 수 있습니다. 미리 감사드립니다.

+0

내 컴퓨터에서이 기능을 실행하는 데 문제가 없습니다. –

+0

@FallaCoulibaly 당신은 당신의 메인 내부에서 그것을 두 번째로 호출 할 수 있고, 그것이 나를 위해했던 것처럼 멈추거나 충돌하는지 볼 수 있습니까? – ShadowGeist

+0

나는 이것을'Integer indexTree = getValue (0, 4);와 같이 main에서 호출했다. –

답변

0

나는이 사이트에서 다른 관련 질문을 철저히 조사한 후에 이미 결론을 내 렸습니다. 당신이 호출 할 때 java.util.NoSuchElementException - Scanner reading user input

는, 첫 번째 방법에서 sc.close는(), 그것은 당신의 스캐너를 닫지 만뿐만 아니라 당신의 System.in 입력 스트림을 닫습니다뿐만 아니라이 그것을 해결 한 문제이다.

제 질문에서 알 수 있듯이 내 코드는 내 메서드 내부에 새 스캐너를 인스턴스화 한 다음 올바른 값을 입력하면 메서드가 스캐너를 닫아 메서드가 호출 된 후 새 입력을 방지합니다. 이 방법에서 내부의 사용자로부터 입력을 검색 할 수 있도록

이 개정 된 바와 같이
public static Integer getValue (Scanner input, int minValue, int maxValue) { 
    int value; 
    value = 0; 
    while (true) { 
     try { 
      value = input.nextInt(); 
      if((value < minValue) || (value > maxValue)) { 
       // ERROR message goes here 
      } else { 
       break; // Input successful, break loop. 
      } 
     } catch (InputMismatchException IME) { 
      // ERROR message goes here. 
      input.nextLine(); // Discards input so user can try again 
     } 
    } 
    return (value); 
} 

스캐너는 이전의 주요 기능 인스턴스화하고, 인수로서 건네 :

이 난 이루어진 수정은 후속 통화.

나는 또한 제 11 장 프로그래밍하는 방법에 Deitel의 책, 자바에서 입력 노트를받는 방법 개선 : 예외 처리를, 그리고 내 특정한 경우에 적용.

0
public static Integer getValue(Integer minValue, Integer maxValue) { 
     Scanner input; 
     input = new Scanner(System.in); 
     int value; 
     while (true) { 

System.out.println("Please enter a value"); 
      if(!input.hasNextInt()) { 
       System.out.println("That's not a number!"); 
       input.next(); // this is important! 
      } 
      value = input.nextInt(); 
      if ((value >= minValue) && (value <= maxValue)) { 
       return value; 
      } else { 
       System.out.println("Wrong value please provide a valid input"); 
      } 
     } 

    } 

시도해보십시오. 당신이하고 싶은 것을 성취하는 데 도움이 될 수 있습니다.

+0

이 답변에는 예외 처리가 없습니다. 필자의 원래 질문에서 알 수 있듯이이 메서드는 주어진 입력이 가비지인지 여부 (예 : 정수가 필요할 때 double 또는 string)인지 여부를 알고 그에 따라 처리해야합니다. – ShadowGeist

+0

@ShadowGeist 제 편집 된 대답을 확인하십시오 –

+0

신뢰할 수있는 출처 (Deitel의 책)에서 직접 선택 되었기 때문에 제 답변이 틀림없이 깨끗하다는 점을 제외하고는 제가 준 대답과 거의 같습니다. 나 좀 도와 줘서 고맙다. – ShadowGeist

관련 문제