2017-10-15 32 views
2

我正在編寫一個代碼,允許用戶決定他們想要什麼類型的投資(年度,月度或季度),並且每種投資類型都與特定的整數相關聯:即Annual = 1,Monthly = 12和Quarterly = 4 。但是,當我每年分配一個值時,我也需要將它與下面我的投資等式中的整數值相關聯,並且完全不知道如何去做。如何將指定的字符串值與整數值相關聯?

import java.util.Scanner; 
import java.lang.Math; 
public class CompoundInterest { 

    public static void main (String [] args) 
      { 
       Scanner cool = new Scanner (System.in); 
    double saving, rate; 
    int principal, years; 
    int choice; 

    System.out.println("Please enter you principal investment:"); 
    /*Print statment prompts user to enter their principal investment*/ 
    principal = cool.nextInt(); 

    System.out.println("Would you like to have a regular investment plan?"); 
    /* Print out statement asks user if they would like to participate in a regular investment plan*/ 
    String question =cool.next(); 

    System.out.println("What type of investment plan would you prefer (Annual, Quarterly, or Monthly)?"); 
    String quest =cool.next(); 

    while (quest.equalsIgnoreCase(("Annual"))) 
    { String Annual="1"; 
     Annual.equals(choice); 

    } 

    System.out.println("Please enter the number of years that you wish to invest for:"); 
    /* Print statement prompts user to enter the number of years that they wish to invest for*/ 
    years = cool.nextInt(); 

    System.out.println("Please enter the return rate per year:"); 
    /* Print statement prompts user to enter the return rate per year*/ 
    rate = cool.nextDouble(); 

    saving = principal*(1+(rate/choice))* Math.pow(choice, years); 
    System.out.printf("%.2f", saving); 
    } 
+0

您可以創建一個數組「invesment」,位置年度,月度和季度使invesment [的Integer.parseInt (Annual)] = your_correlated_value; – Jar3d

回答

1
  • 一旦投資計劃的類型回答,您需要檢查quest變量匹配任何您所期待的字符串,即AnnualQuarterly,或Monthly的。
  • 如果quest匹配任何的選擇,你指定一個正確的值choice變量,即,1,4,或12
  • 你也可能還需要如果答案沒有想到的情況下,匹配任何正確的選擇。

    if ("Annual".equalsIgnoreCase(quest)) { 
        choice = 1; 
    } else if ("Quarterly".equalsIgnoreCase(quest)) { 
        choice = 4; 
    } else if ("Monthly".equalsIgnoreCase(quest)) { 
        choice = 12; 
    } else { 
        //you need to do something here. 
    } 
    
0

我會建議使用定義的詮釋你想要一個枚舉。我會打電話給枚舉計劃和INT項:

public enum Plan { 
    ANNUAL(1), 
    QUARTERLY(4), 
    MONTHLY(12); 

    int term; 

    Plan(int term) { 
     this.term = term; 
    } 
}; 

你會在你的代碼像這樣使用(它取代INT選擇):

Plan plan = Plan.valueOf(quest.toUpperCase()); 
    saving = principal * (1 + (rate/plan.term)) * Math.pow(plan.term, years); 

我想你會需要不同您的計算版本。如果你在enum中添加了一個方法來打開enum的值,enum方法將很容易支持。您可以計算出不同的計算實現並在case語句中定義它們。

double calculateSavings(int principal, double rate, int years) { 
     switch (this) { 
      case ANNUAL: 
      case QUARTERLY: 
      case MONTHLY: 
      default: 
       return principal * (1 + (rate/term)) * Math.pow(term, years); 
     } 
    } 

如果你走這條路線,你會用它在你的代碼是這樣的:

// saving = principal * (1 + (rate/plan.term)) * Math.pow(plan.term, years); 
    saving = plan.calculateSavings(principal, rate,years); 
相關問題