当试图从标准中读取int时,我得到一个编译错误。
System.out.println("Hello Calculator : n");
int a=System.in.read();
程序抛出异常:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type IOException at SamplePackege.MainClass.main(MainClass.java:15)
如何修复此错误?
My Code:
try {
Scanner sc = new Scanner(System.in);
int a=sc.nextInt();
} catch (Exception e) {
// TODO: handle exception
}
in.read()可以抛出IOException类型的检查异常。
你可以在这里阅读Java中的异常处理。
你可以改变你的程序来抛出IOException,或者你可以把读放到try catch块中。
try{
int a=System.in.read();
catch(IOException ioe){
ioe.printStackTrace();
}
或
public static void main(String[] args) throws IOException {
System.out.println("Hello Calculator : n");
int a=System.in.read();
}
程序没有错误。
方法read()
要求您在出现问题时捕获Exception
。
将方法包含在try/catch
语句中:
try {
int a = System.in.read();
...
}
catch (Exception e) {
e.printStackTrace();
}
在任何情况下我强烈建议您使用文档和/或Java教程,其中清楚地说明了这些事情。不使用它们的编程是毫无意义的。这样可以省去很多麻烦,还可以节省时间。