2014-04-25 2 views
0

ScannerDataInputStream을 사용하여 사용자로부터 의견을 얻으려고합니다.아래 시나리오에서 왜 다른 유형의 예외가 발생합니까?

시나리오 1 :

Scanner scanner = new Scanner(System.in); 
System.out.print("Enter a number: "); 
double d1 = scanner.nextDouble(); 

시나리오 2 : 여기 내가 사용 내 코드는

DataInputStream din = new DataInputStream(System.in); 
System.out.print("Enter a number: "); 
double d2 = Double.parseDouble(in.readLine()); 

ABC 같은 일부 문자로 입력을 제공 :

시나리오 1에서 나는 받고 있습니다 InputMismatchException입니다. 시나리오 2에서 나는 받고 있습니다 NumberFormatException입니다.

Scanner이 다른 예외를 throw합니까? 누군가 명확히 해줄 수 있습니까?

답변

1

Scanner.nextDouble()의 JavaDoc을 말한다 :

Scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched. 

Returns: 

The double scanned from the input 

Throws: 

InputMismatchException - if the next token does not match the Float regular expression, or is out of range 
NoSuchElementException - if the input is exhausted 
IllegalStateException - if this scanner is closed 

Scanner.class 소스 확인 :

public double nextDouble() { 
     // Check cached result 
     if ((typeCache != null) && (typeCache instanceof Double)) { 
      double val = ((Double)typeCache).doubleValue(); 
      useTypeCache(); 
      return val; 
     } 
     setRadix(10); 
     clearCaches(); 
     // Search for next float 
     try { 
      return Double.parseDouble(processFloatToken(next(floatPattern()))); 
     } catch (NumberFormatException nfe) { 
      position = matcher.start(); // don't skip bad token 
      throw new InputMismatchException(nfe.getMessage()); 
    } 
} 

Double.parseDouble()이 (시나리오 2에 따라) NumberFormatException를 발생하는 경우, 구문 분석을 시도하고 Scanner.nextDouble() 던져 InputMismatchException (시나리오 1대로).

관련 문제