Java每月复利

时间:2014-11-02 23:43:03

标签: java string

我需要编写一个程序,根据用户输入值使用for循环计算每月复利。但我遇到了一些问题。

示例输入和输出应如下所示:

请输入以下内容:本金,利率,期限>> 1000 5 54个月

Month:  Interest:   Principal:
   1    $4.17       $1004.17 
   2    $4.18       $1008.35 
   etc. etc.        etc.

我的问题是字符串输入验证。如果用户键入除月或年之外的任何内容,则应通知他们并重新提示再次输入。然而,根据我目前的代码,它只是要求用户输入数月或数年,即使他们已进入数月或数年。

public Calculator() {
    Scanner input = new Scanner(System.in);
    boolean error = false;

    while (!error) {
        System.out
                .print("Please input the following: principal, interest rate, term >> ");
        double principal = input.nextDouble();
        double interest_rate = input.nextDouble();
        int term = input.nextInt();
        String MonthOrYear = input.nextLine();
        double amount = 0;

        if (interest_rate <= 0 || term <= 0 || principal <= 0) {
            System.out
                    .println("The term, interest rate and principal must be greater than zero");
            continue;
        }
        if (!MonthOrYear.equals("month") || (!MonthOrYear.equals("year"))) {
            System.out.println("Please input either month or year");
            continue;
        }

        System.out.println("Month:  " + "  Interest:  " + "Principal:  ");

        for (int month = 1; month <= term; month++) {
            double interest = principal * interest_rate / 100;
            principal = principal + interest;
            System.out.printf("%4d %10.2f %10.2f\n", month, interest,
                    principal);

        }
        break;
    }
}

1 个答案:

答案 0 :(得分:0)

使用nextInt和nextLine时常见错误。 改变你的行:

String MonthOrYear = input.nextLine();  

由:

String MonthOrYear = input.next();