【发布时间】:2014-08-21 13:48:14
【问题描述】:
我正在编写一个用于获取一些非常大的数字(10^8 顺序)的代码,我的程序抛出了数字格式异常。这是代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
class sticker
{
public static void main(String gs[])
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
long a[]=new long[40];
int n=0,i,k=0;
String x;
try {
x=in.readLine();
n=Integer.parseInt(x); // n is the number of inputs
for(i=0;i<n;i++)
{
x=in.readLine();
a[i]=Long.parseLong(x);
}
for(i=0;i<n;i++)
{
if(a[i]<=300000000)
k++;
}
} catch (IOException e) {
System.out.println("error");
} catch(NumberFormatException nfe) {
System.out.println("NumberFormatException: "+nfe.getMessage());
}
System.out.println("\n");
System.out.println(k);
}
}
谁能告诉我哪里做错了??
错误:
2
18 200000000
NumberFormatException: For input string: "18 200000000"
0
【问题讨论】:
-
"18 200000000" 显然不是有效数字,因为有空格
-
我输入了 2 作为输入的数量,所以我必须给出 2 个数字,我给出了 18 和 200000000 作为我的输入。
-
空格不是结束我认为的数字的分隔符!理想情况下是输入 !!??!?!
-
但是你用
a[i]=Long.parseLong(x);解析整行。在调用parseLong()之前,您需要将尝试输入的两个数字分开。 -
我认为您不必担心
Scanner和BufferedReader之间的运行时效率差异。对于编码人员(即您)来说,使用Scanner比尝试自己解析字符串要容易得多。
标签: java arrays exception-handling long-integer numberformatexception