有人能帮我解决我的问题吗。我是Java编程的初学者。以前,当我没有声明抛出IOException时,它给了我一个错误:
线程"main“java.lang.RuntimeException中的异常:不可编译的源代码-未报告的异常java.io.IOException;必须捕获或声明抛出
该方案如下:
import java.io.*;
public class addition {
public static void main(String array[])throws IOException
{
InputStreamReader i = new InputStreamReader(System.in);
BufferedReader b = new BufferedReader(i);
System.out.println("Enter first number : ");
int a1 = Integer.parseInt(b.readLine());
System.out.println("Enter second number : ");
int a2 = Integer.parseInt(b.readLine());
int sum = a1 + a2 ;
System.out.println("addition"+sum);
}
}发布于 2015-05-14 18:19:37
如果在尝试从输入流读取时出现I/O故障,BufferedReader函数readLine()将抛出一个IOException。在Java中,如果出现异常,必须使用try catch语句来处理它们:
import java.io.*;
public class addition {
public static void main(String array[])throws IOException
{
InputStreamReader i = new InputStreamReader(System.in);
BufferedReader b = new BufferedReader(i);
System.out.println("Enter first number : ");
// Attempt to read in user input.
try {
int a1 = Integer.parseInt(b.readLine());
System.out.println("Enter second number : ");
int a2 = Integer.parseInt(b.readLine());
int sum = a1 + a2 ;
System.out.println("addition"+sum);
}
// Should there be some problem reading in input, we handle it gracefully.
catch (IOException e) {
System.out.println("Error reading input from user. Exiting now...");
System.exit(0);
}
}
}https://stackoverflow.com/questions/30244337
复制相似问题