Java 我收到此代码的数字格式异常
我得到了这个例外 主线程java.lang.NumberFormatException中出现异常:null java:542 java:615 在Test.mainMain.java:10 守则:Java 我收到此代码的数字格式异常,java,arrays,exception,numberformatexception,Java,Arrays,Exception,Numberformatexception,我得到了这个例外 主线程java.lang.NumberFormatException中出现异常:null java:542 java:615 在Test.mainMain.java:10 守则: import java.util.*; import java.io.*; class Test { public static void main (String[] args) throws IOException { BufferedRe
import java.util.*;
import java.io.*;
class Test {
public static void main (String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a[]=new int[10],flag=1;
System.out.println("Enter The Nos.");
for(int i=0;i<=9;i++)
a[i]=Integer.parseInt(br.readLine());
int i=0;
do{
if(a[i]!=42)
System.out.println(a[i]);
else{ flag=0;break;
} i++;
}while(flag==1);
}
}
它在eclipse上运行正常,但在其他IDE上,它给出了这个异常。问题在于这一行a[i]=Integer.parseIntbr.readLine 您应该检查br.readLine!=在执行上面的行之前为null 您正在尝试将null解析为整数。这就是错误所暗示的 编辑: 根据,如果到达流的结尾,readLine将返回null 您的代码应该如下所示:
import java.util.*;
import java.io.*;
class Test {
public static void main (String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a[]=new int[10],flag=1;
System.out.println("Enter The Nos.");
for(int i=0;i<=9;i++) {
String num = br.readLine();
if(num != null) {
a[i]=Integer.parseInt(num);
} else {
//a[i] = 0; // You might want to assign a[i] to some integer if the input number is null
}
}
int i=0;
do{
if(a[i]!=42)
System.out.println(a[i]);
else{ flag=0;break; }
i++;
}while(flag==1 && i < 10);
}
}
异常具有很好的描述性,您正在尝试将null作为int进行解析。在调用parseInt之前进行null检查。检查br like的null功能很好
br.readLine() != null
然后解析它
您的输入可能包含一个空格,因此java无法将其转换为数字,例如4 5。为此,您可以用替换所有空格,然后尝试将其转换为数字
br.readLine().replaceAll("\\s+", "");
您的代码如下所示
import java.util.*;
import java.io.*;
class Test {
public static void main (String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a[]=new int[10],flag=1;
System.out.println("Enter The Nos.");
if(br.readLine()!=null)
{
for(int i=0;i<=9;i++) {
String num = br.readLine().replaceAll("\\s+", "");
if(num != null) {
a[i]=Integer.parseInt(num);
} else {
//a[i] = 0; // You might want to assign a[i] to some integer if the input number is null
}
}
int i=0;
do{
if(a[i]!=42)
System.out.println(a[i]);
else{ flag=0;break; }
i++;
}while(flag==1 && i < 10);
}
}
}
你能给我看看你对这个程序的输入吗?异常信息很清楚。你不明白什么?试试我答案中的代码。这样就可以了。在尝试将br.readLine的结果转换为整数之前,请先将其打印出来。这将为您提供有关如何修复程序的线索。是的,但是为什么流只有在Eclipse中才会出现null?但是请记住,如果字符串不包含可解析的int,则会引发NumberFormatException。但是包括null,正如Ashutosh所述,这里的情况是:它不是出现null的流。相反,readline才是>>returning@AadityaGavandalkar在这种特殊情况下,它之所以发生是因为null。线程主线程java.lang.NumberFormatException中出现异常:Null非常感谢mate。但现在,如果一个[i]=42适用于完整数组。也就是说,如果在数组中找不到42,则会出现ArrayIndexOutOfBoundsException。非常感谢。但这两种说法都不起作用。也许我在这方面太差了。你能把这些语句放在我代码的正确位置吗