尝试编译简单java程序时出现NumberFormatException
这是我的代码:尝试编译简单java程序时出现NumberFormatException,java,exception,numberformatexception,Java,Exception,Numberformatexception,这是我的代码: public class RetailMarket { public static void main(String[] args) throws IOException { int i,ch1,ch2,type,total=0,kg=0; System.out.println("What would you like to buy::"); System.out.println("(1)Grains (2)Oil");
public class RetailMarket {
public static void main(String[] args) throws IOException {
int i,ch1,ch2,type,total=0,kg=0;
System.out.println("What would you like to buy::");
System.out.println("(1)Grains (2)Oil");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
ch1 = Integer.parseInt(br1.readLine()); // exception thrown here
}
}
每次运行时,这是我的输出:
What would you like to buy::
(1)Grains (2)Oil
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:454)
at java.lang.Integer.parseInt(Integer.java:527)
at RetailMarket.main(RetailMarket.java:16)
我不明白为什么会发生这种
NumberFormatException
;有人能解释一下原因吗?如果br1.readLine()
不能被解析为int,就会出现异常。
您应该验证此字符串是否只包含数字,或者捕获异常。您正在将
null
传递给Integer.parseInt()
。这意味着br1.readLine()
正在返回null
。发生这种情况的唯一方法是到达流的末尾。这意味着您设法没有正确初始化系统.in
。尝试在与编译类相同的目录下,使用java RetailMarket
从命令行运行该程序。这段代码在我运行时运行良好
此外,如果输入无效,如
,则应考虑捕获<代码> NoMbFrimeExtExt/Cuth>并保持程序运行。try {
ch1 = Integer.parseInt(br1.readLine());
} catch (NumberFormatException e) {
// invalid input
}
无需使用BufferedReader,使用扫描器直接读取整数而无需解析 试试这个:
public class RetailMarket{
public static void main(String[] args) throws IOException {
int i,ch1,ch2,type,total=0,kg=0;
System.out.println("What would you like to buy::");
System.out.println("(1)Grains (2)Oil");
Scanner sc = new Scanner(System.in);
ch1 = sc.nextInt();
}
}
错误发生在运行程序而不是编译程序时。出于某种原因,运行此操作时,您似乎没有控制台。我建议尝试在命令行上运行它。顺便说一句,您不应该多次在中包装
系统,因为它可能会放弃输入。您是否在每次迭代中都关闭br1?给我们看看剩下的代码。“马丁,如果它有效,你可以考虑接受这个答案:”