我在 Code Chef 上编写了一个程序。我在 Eclipse IDE 上得到了正确的输出,当我提交它时,CodeChef IDE 上显示的输出是:
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
at Prog1.stop(Main.java:16)
at Prog1.main(Main.java:50)
这是问题链接:https://www.codechef.com/problems/TEST
这是我的问题解决方案: //生命宇宙和万事万物
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Prog1
{
public static void stop() throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s1=br.readLine();
int x=Integer.parseInt(s1);
int ar[]=new int[x];
int k=0;
for(int i=0;i<x;i++)
{
BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
String s2=br1.readLine();
int p=Integer.parseInt(s2);
ar[k++]=p;
}
for(int m=0;m<x;m++)
{
System.out.println(ar[m]);
}
for(int y=0;y<x;)
{
if(ar[y]!=42)
{
System.out.println(ar[y]);
y++;
}
else
{
break;
}
}
}
public static void main(String s[]) throws IOException
{
stop();
}
}
最佳答案
直接原因是您将 null
传递到 Integer.parseInt
中。接下来您需要弄清楚为什么会发生这种情况...
您正在创建一个新的 BufferedReader
,在每次迭代中包装 System.in
...这可能读取的不仅仅是一行,这意味着一些输入行实际上被吞没了。
只需在开始时创建一个 BufferedReader
,并将其用于整个程序。您还可以检查 readLine
的返回值是否为 null
,但由于这将表明数据无效,因此按照它已经在做的方式抛出它并不可怕。 ..
关于java - 为什么我收到数字格式异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31959306/