When trying to write read an int from standard in I'm getting a compile error.
System.out.println("Hello Calculator : \n");
int a=System.in.read();
The program throws an exception:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type IOException at SamplePackege.MainClass.main(MainClass.java:15)
How do I fix this error?
My Code :
try {
Scanner sc = new Scanner(System.in);
int a=sc.nextInt();
} catch (Exception e) {
// TODO: handle exception
}
解决方案
in.read() can throw a checked exception of type IOException.
You can read about Exception Handling in Java Here.
You can either change your program to throw an IOException, or you can put the read in a try catch block.
try{
int a=System.in.read();
catch(IOException ioe){
ioe.printStackTrace();
}
or
public static void main(String[] args) throws IOException {
System.out.println("Hello Calculator : \n");
int a=System.in.read();
}