2011-05-01 106 views
2

我知道我在这里做的事情非常错误,但我会坦率的说,在这里我的java知识很薄弱。每当我打电话dataIn.readLine()我得到这个编译时错误java中的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在这里编译它也得到了相同的结果。

回答

4

的readLine()可以抛出IOException。你需要把它包装在一个try-catch块中,如果它出现就捕获这个异常,然后以一种对你正在做的事情理智的方式处理它。如果readLine()抛出异常,控制将立即从try块中流出并进入catch块。

try 
{ 
    dataIn.readLine(); 
    // ... etc 
} 
catch(IOException e) 
{ 
    // handle it. Display an error message to the user? 
} 
+0

这两个建议都可以工作,但是因为你的答案是最正确的答案,所以你得到了接受的答案。 – VoronoiPotato 2011-05-01 01:46:06