我知道我在这里做了一些非常错误的事情,但我坦白地说,我对java的了解非常薄弱。每当我调用 dataIn.readLine() 时,我都会收到此编译时错误
unreported exception java.io.IOException; must be caught or declared to be thrown
这是代码,我知道命名约定很糟糕,而且它几乎没有任何作用。
import java.io.*;
public class money {
public static void main( String[]args ){
String quarters;
String dimes;
String nickels;
String pennies;
int iquarters;
int idimes;
int inickels;
int ipennies;
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
System.out.println( "Enter the number of quarters. " );
quarters = dataIn.readLine();
System.out.println( "Enter the number of dimes" );
dimes = dataIn.readLine();
System.out.println( "Enter the number of nickels" );
nickels = dataIn.readLine();
System.out.println( "Enter the number of pennies" );
pennies = dataIn.readLine();
iquarters = Integer.parseInt( quarters );
idimes = Integer.parseInt( dimes );
inickels = Integer.parseInt( nickels );
ipennies = Integer.parseInt( pennies );
}
}
http://www.ideone.com/9OM6O 也在这里编译,结果相同。
更改此:
public static void main( String[]args ){
至:
public static void main( String[]args ) throws IOException {
要了解为什么需要这样做,请阅读以下内容:http://download.oracle.com/javase/tutorial/essential/exceptions/
readLine()
可以抛出 IOException。您需要将其包装在一个 try-catch
块中,以便在出现异常时捕获该异常,然后以适合您正在执行的操作的方式处理它。如果 readLine()
抛出异常,控制将立即流出 try 块并进入 catch 块。
try
{
dataIn.readLine();
// ... etc
}
catch(IOException e)
{
// handle it. Display an error message to the user?
}