2014-10-10 1 views
0

키보드에서 가져온 문자열 값을 int 값으로 변환하려고합니다. 나는 전에 이런 식으로 일을하지만 지금은 오류를 얻고있는 입력 코드는 NumberFormatException.forInputString스캐너에서 입력을 사용하여 int로 변환하는 문자열

Scanner input = new Scanner(System.in); 
String choice = ""; 
int numberChoice; 
System.out.println("Please select one of the following options"); 
choice = input.nextLine(); 
numberChoice = Integer.parseInt(choice); /*I am getting the error on this line*/ 

진술했다 :

Data[] temperatures = new Data[7]; 

for(int i = 0; i < temperatures.length; i++) 
    { 
     System.out.println("Please enter the temperature for day " + (i+1)); 
     temperatures[i] = new Data(input.nextDouble()); 
    } 
+0

http://stackoverflow.com/questions/18711896/how-to-resolve-java-lang-numberformatexception- :

는이 문제를 해결하려면 줄 바꿈을 소비하는 추가 nextLine()를 호출해야 for-input-string-na – generalcrispy

+0

유효한 번호가 아닌 무언가를 입력했을 수도 있습니다. 그게 문제가 아니라면, 우리가 볼 수없는 코드에서 문제를 일으키는 다른 것이 있습니다. 프로그램에서 아무 것도 타이핑 할 기회를주지 않고 예외를 제공 했습니까? 위의 코드 이전에 다른 입력이 있습니까? – ajb

+0

유효한 int 변수를 입력하고 있습니다. 네, 입력에 뭔가가 있습니다. 원래 질문에 덧붙여졌습니다. – destroted

답변

0

nextDouble() 또는 nextInt()과 같이 하나의 토큰을 찾는 Scanner 메서드를 사용하면 스캐너는 해당 토큰의 문자를 사용하지만 o 줄의 끝에서 줄 바꿈 문자를 사용합니다.

다음번 Scanner 호출이 다른 nextDouble(), nextInt() 등과 같은 호출 인 경우이 호출은 줄 바꿈을 건너 뛰기 때문에 괜찮습니다.

다음 호출이 nextLine()이면 ""을 반환합니다. nextLine()은 다음 줄 바꿈 문자까지 모든 것을 반환합니다. nextDouble() 호출 후에 줄 바꿈 문자를 아직 소비하지 않았기 때문에, 줄 바꿈을 멈추고 빈 줄을 반환하고 다른 줄을 입력 할 기회가 없습니다.

for(int i = 0; i < temperatures.length; i++) 
    { 
     System.out.println("Please enter the temperature for day " + (i+1)); 
     temperatures[i] = new Data(input.nextDouble()); 
    } 
input.nextLine();  // Add this to consume the newline 
String choice = ""; 
int numberChoice; 
System.out.println("Please select one of the following options"); 
choice = input.nextLine(); 
numberChoice = Integer.parseInt(choice); 
+0

감사합니다, 그 여분의 ""에 대해 잊어 버렸습니다! – destroted

1

당신은 정수로 문자열을 변환 한 후 대신 choice = input.nextLine();numberChoice = input.nextInt();을 사용할 수 있습니다

+1

nextInt는 결과를 얻기 위해 parseInt를 사용하기 때문에, 원래 코드와 똑같은 경우 실패합니다. –

0

실수로 입력란에 공백이나 숫자가 아닌 문자를 입력하지 않았는지 확인하십시오. 코드 스 니펫을 실행했는데 정상적으로 작동합니다.

Please select one of the following options 
6546a 
Exception in thread "main" java.lang.NumberFormatException: For input string: "6546a" 
    at java.lang.NumberFormatException.forInputString(Unknown Source) 
    at java.lang.Integer.parseInt(Unknown Source) 
    at java.lang.Integer.parseInt(Unknown Source) 
    at PrimeNumbers.main(PrimeNumbers.java:12) 
0

int로 구문 분석 할 수있는 내용을 입력하면 정상적으로 작동합니다. 예를 들어 잘못된

무슨 일이 일어나고 있는지 확인하기 위해 try 블록과 출력 오류와 선택의 내용에 잘못된 줄 바꿈이 시도 : 내 컴퓨터에

try { 
    numberChoice = Integer.parseInt(choice); 
} 
catch (NumberFormatException nfe){ 
    System.out.println("Failed to parse: ##"+choice+"##"); // mark off the text to see whitespace 
} 

을,이

/Users/jpk/code/junk:521 $ java SO 
Please select one of the following options 
two 
Failed to parse: ##two## 
생산
관련 문제