2014-10-10 42 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- for-input-string-na – generalcrispy 2014-10-10 17:29:10

+0

您可能輸入的內容不是有效的數字。如果這不是問題,那麼還有其他問題導致我們看不到的代碼出現問題。程序是否給你一個例外,但你沒有機會輸入任何內容?上述代碼之前是否還有其他輸入? – ajb 2014-10-10 17:38:39

+0

我輸入有效的int變量。是的,有輸入的東西,我已經把它添加到原來的問題 – destroted 2014-10-10 17:41:20

回答

0

當您使用Scanner方法查看一個令牌(如nextDouble()nextInt())時,掃描程序將消耗該令牌中的字符,但它會將n ot消耗行尾的換行符。

這很好,如果下一個Scanner電話是另一個nextDouble(),nextInt()等,因爲那麼該呼叫將跳過換行。

但是,如果下一個電話是nextLine(),它將返回""nextLine()將返回一切到下一個換行符;並且由於它在調用nextDouble()之後尚未消耗換行符,因此它將停在該換行符處,並返回一個空字符串,而不會讓您有機會輸入另一行。

爲了解決這個問題,你需要調用額外的nextLine()消耗換行符:

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 2014-10-10 17:50:17

1

可以使用numberChoice = input.nextInt();代替choice = input.nextLine();,然後將字符串轉換爲整數

+1

由於nextInt使用parseInt來得到它的結果,這將在原來的代碼完全相同的情況下失敗。 – 2014-10-10 17:39:05

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##