2014-11-19 2 views
0

검색했지만 실제로 코드에서 문제가있는 것 같지 않습니다. 제발 도와주세요!"스레드의 예외"main "java.util.InputMismatchException"**

코드는 내가 질문 3 응답 할 때이 내가 오류이지만, 컴파일 :

Exception in thread "main" java.util.InputMismatchException 
     at java.util.Scanner.throwFor(Unknown Source) 
     at java.util.Scanner.next(Unknown Source) 
     at java.util.Scanner.nextDouble(Unknown Source) 
     at ForgetfulMachine.main(ForgetfulMachine.java:16) 

을 그리고 이것은 내 코드입니다 :

import java.util.Scanner; 

public class ForgetfulMachine 
{ 
    public static void main(String[] args) 
    { 
     Scanner keyboard = new Scanner(System.in); 

     System.out.println("What city is the capital of Germany?"); 
     keyboard.next(); 

     System.out.println("What is 6 divided by 2?"); 
     keyboard.nextInt(); 

     System.out.println("What is your favorite number between 0.0 and 1.0?"); 
     keyboard.nextDouble(); 

     System.out.println("Is there anything else you would like to tell me?"); 
     keyboard.next(); 
    } 
} 
+0

'nextDouble()'전에'nextLine()'호출을 추가해보십시오. – August

+2

독일에 계시거나 부동 소수점 숫자에'.' 대신','를 사용하는 곳이 있습니까? '0,5 '라고 대답 해주세요 (저에게 효과가 있습니다) – zapl

+0

@zapl Thank you! 그리고 나는 독일에있다! – tyskmeister

답변

2

Scanner이 예외가 발생합니다. 특히, 귀하의 경우, 잘못된 소수 구분 기호가 사용되는 경우. .,은 공통 로케일 별 소수 구분 기호입니다. 또한

System.out.println(
    javax.text.DecimalFormatSymbols.getInstance().getDecimalSeparator() 
); 

참조 : 소수 구분 당신은 사용할 수 있습니다 기본 로케일이 무엇인지

을 찾으려면

0

아무것도 코드에 이상이 없습니다. 데이터를 입력 할 때 유형을 존중하십시오. 정수 등을 기다리는 동안 double을 입력하지 마십시오. 사용자가 예상 값을 준수 할 때만 데이터를 수락하는 방어 코딩을 적용하여 이러한 유형의 오류를 해결할 수 있습니다. 항목이 스캐너의 로케일의 잘못된 형식으로되어있는 경우

public static void main(String[] arg) { 
    Scanner keyboard = new Scanner(System.in); 

    System.out.println("What city is the capital of Germany?"); 
    keyboard.nextLine(); 

    System.out.println("What is 6 divided by 2?"); 
    boolean isNotCorrect = true; 

    while(isNotCorrect){ 
     isNotCorrect = true; 
     try { 
      Integer.valueOf(keyboard.nextLine());  
      isNotCorrect = false; 
     } catch (NumberFormatException nfe) { 
      System.out.println("Enter an integer value"); 
     } 
    } 


    System.out.println("What is your favorite number between 0.0 and 1.0?"); 
    isNotCorrect = true; 

    while(isNotCorrect){ 

     try { 
      Double.valueOf(keyboard.nextLine()); 
      isNotCorrect = false; 
     } catch (NumberFormatException nfe) { 
      System.out.println("Enter a double value"); 
     } 
    } 

    System.out.println("Is there anything else you would like to tell me?"); 
    keyboard.next(); 
}  
관련 문제