Java 从扫描仪输入的字符串到整数的转换
我正在尝试将从键盘获取的字符串值转换为int值。我以前也这样做过,但现在我遇到了一个错误,它表示Java 从扫描仪输入的字符串到整数的转换,java,Java,我正在尝试将从键盘获取的字符串值转换为int值。我以前也这样做过,但现在我遇到了一个错误,它表示NumberFormatException.forInputString Scanner input = new Scanner(System.in); String choice = ""; int numberChoice; System.out.println("Please select one of the following options"); choice = input.nextLi
NumberFormatException.forInputString
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());
}
Data[]温度=新数据[7];
对于(int i=0;i
您可以使用numberChoice=input.nextInt()代码>而不是choice=input.nextLine()编码>,然后将字符串转换为整数确保不会在输入行中意外键入空格或非数字字符。我运行了你的代码片段,它运行得很好
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)
假设您输入了可以解析为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##
当您使用查看一个标记的Scanner
方法时,例如nextDouble()
或nextInt()
,扫描器将使用该标记中的字符,但不会使用行尾的换行符
如果下一个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);
for(int i=0;i
您可能键入了无效数字。如果这不是问题所在,那么在代码中还有一些我们看不到的问题。程序是否给了你一个例外而没有给你输入任何东西的机会?在上面的代码之前还有其他输入吗?我正在输入有效的int变量。是的,输入中有一些内容,我已将其添加到原始问题中,因为nextInt使用parseInt获得其结果,这将在与原始代码完全相同的情况下失败。谢谢,我忘记了额外的“”!