2014-11-02 50 views
-1

我需要編寫一個程序來計算每月複利興趣使用for循環根據用戶輸入值。但我有一些問題。Java每月複利

例輸入和輸出應該是這樣:

請輸入以下內容:本金,利率,期限>> 1000 554個月

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; 
    } 
} 
+2

如果這個條件總是真(MonthOrYear.equals( 「月」)||(MonthOrYear.equals( 「年」))!) ,不管MonthOrYear的值如何,它應該是&&而不是|| – Michael 2014-11-02 23:48:11

+1

http://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – Deltharis 2014-11-02 23:57:25

回答

0

這是nextInt和nextLine使用時的常見錯誤。 更改行:

String MonthOrYear = input.nextLine(); 

由:

String MonthOrYear = input.next();