2017-10-15 33 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); 
相关问题