2014-10-10 59 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##