![](/img/trans.png)
[英]java - Exception in thread “main” java.lang.NumberFormatException: For input string: “” at
[英]Exception in thread “main” java.lang.NumberFormatException: For input string: “”
对于以下小代码,我得到了错误...
import java.io.*;
class test
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i;
System.out.println("Enter no of processes ");
int no_of_process=Integer.parseInt(br.readLine());
int process[]=new int[no_of_process];
System.out.println("Enter the values");
for(i=0;i<no_of_process;i++)
process[i]=Integer.parseInt(br.readLine());
for(i=0;i<no_of_process;i++)
System.out.println(process[i]);
}
}
输入:
Enter no of processes
5
Enter the values
1
2
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:470)
at java.lang.Integer.parseInt(Integer.java:499)
at test.main(test.java:17)
Process completed.
我想我已经正确编写了代码,并且还给出了正确的整数输入。 如何在不使用任何显式异常处理语句的情况下摆脱上述错误?
谢谢大家的回答...它正在工作。 但是我心中有一个新问题。
我在代码中尝试了以下修改并执行了它。 令我惊讶的是,输入被正确接受,没有任何运行时错误。
for(i=0;i<no_of_process;i++)
{
System.out.println(Write anything or even keep it blank);
process[i]=Integer.parseInt(br.readLine());
}
通过在for循环中的输入语句之前(甚至之后)添加一个Print语句,我的程序可以正常工作,并且在提供输入时不会引发异常。
你们能解释这背后的原因吗?
同样,如果我从此处删除Print语句,则会重复出现相同的错误。 我真的很困惑背后的原因。 请帮忙。
没有任何错误处理语句? 在尝试解析br.readLine()之前先检查它是否返回“”,如下所示:
String line = br.readLine();
if(!String.isEmpty(line))
{
//Do stuff
}
else
{
//Do other stuff
}
如何在不使用任何显式异常处理语句的情况下摆脱上述错误?
for (i = 0; i < no_of_process; i++) {
String input;
do {
input = br.readLine();
if (isInteger(input)) {
process[i]=Integer.parseInt(input);
} else {
//error handling here
System.err.println("you entered an invalid input");
}
} while(isInteger(input));
}
isInteger
看起来像这样:
public static boolean isInteger(String s)
{
try {
Integer.parseInt(s);
}
catch (Exception e) {
return false;
}
return true;
}
我想我写的正确,并且给出了正确的整数输入。
我认为不是;)我认为您没有输入任何内容就按了返回键
尝试这个:
import java.io.*;
public class test
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i;
System.out.println("Enter no of processes ");
try{
int no_of_process=Integer.parseInt(br.readLine());
int process[]=new int[no_of_process];
System.out.println("Enter the values");
for(i=0;i<no_of_process;i++)
process[i]=Integer.parseInt(br.readLine());
for(i=0;i<no_of_process;i++)
System.out.println(process[i]);
}
catch(NumberFormatException n)
{
System.out.println(n.getMessage());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.