0

以下程序旨在计算简单的利息给定公式 i = p*r*t,给定用户输入并将其放入自己的方法(必须),但是,在运行它时,我收到错误“未处理的异常类型 IOException。 ..” 我之前尝试实现一个 try catch 块,但它导致了更多错误

import java.io.*;

public class cInterest {

    public static void main(String[] args) throws IOException {

    }

    public static double balance(double principal, double rate, double years) {

        double amount = 0;

        String input;
        BufferedReader myInput = new BufferedReader(new InputStreamReader(
                System.in));

        System.out.print("How much would you like to take out? ");
        input = myInput.readLine();
        principal = Double.parseDouble(input);

        System.out.print("Enter the interest rate: ");
        input = myInput.readLine();
        rate = Double.parseDouble(input);

        for (int i = 1; i < years; i++) {
            amount = principal * rate * years;
            amount += principal;
        }
        return amount; // - principal;

    }
}
4

3 回答 3

0
myInput.readLine(); can throw `IOException` so you **must** handle it somewhere.

利用:

try {
    myInput.readLine();
} catch (IOException e){
    e.printStackTrace();
}

并尝试解决其他问题。还要从方法中删除throws声明。main

于 2013-03-07T14:11:00.513 回答
0

最简单的解决方法是简单地声明您的方法抛出(如果您从那里调用,您也IOException需要对方法执行此操作):mainbalance

public static double balance(double principal, double rate, double years) throws IOException {

public static void main(String[] args) throws IOException {

您可能想尝试使用Scanner而不是InputStreamReader- 它更容易用于此类事情

Scanner sc = new Scanner(System.in);

为了执行您的代码,您需要从main方法中调用它:

public static void main(String[] args) throws IOException {
    balance(0, 0, 0);
}     
于 2013-03-07T14:11:03.250 回答
0

但是,在运行它时,我收到错误“未处理的异常类型 IOException...”

程序运行时不会出现异常(实际上,您的main()方法仍然是空的,因此不会执行任何操作),但是编译器在编译代码时会出现此错误。

你要么需要捕获异常,要么让你的方法让它继续下去,比如

public static double balance(double principal, double rate, double years) throws IOException { ... }

背景是您myInput.readLine(); 可以抛出IOException- 这需要传递给调用方法,如上所示,或者需要由 a 处理try{}-catch()-block

try {
    input = myInput.readLine();
} catch(IOException ioex) {
    ioex.printStackTrace();
    // ... additional code to handle the exception properly
}

您还应该避免main()抛出异常 - 如果您从上面选择第一种方法并让 balance 抛出异常,请IOException在 main 方法中处理它。以下代码片段还显示了如何调用该balance方法:

public static void main(String[] args) {
    try {
        balance(1, 2, 3);
    } catch(IOException ioex) {
        ioex.printStackTrace();
        // ... additional code to handle the exception properly
    }
}

另见课程:例外

于 2013-03-07T14:10:31.400 回答