在while循环中更改double的值

时间:2014-10-05 01:46:27

标签: java while-loop

我的学校代码出现问题我试图修改双" original_amount"以便while循环可以更新信息并一次又一次地打印

它应打印此阈值为1,000美元,较小的利率为0.9%,较大的利率为1.5%,您投资990美元,并且您希望追踪此金额3年

Report on John Johnson's saving account:
Original amount              990.00

Year 1:
effective interest rate        0.9%
amount gained                  8.91
amount at the end of Year    998.91

Year 2:
effective interest rate        0.9%
amount gained                  8.99
amount at the end of Year   1007.90

Year 3:
effective interest rate        1.5%
amount gained                 15.12
amount at the end of Year   1023.02

Thanks for using our bank! 

这是我的代码:

  {
Scanner input=new Scanner(System.in);
System.out.println("Enter your name");
String name=input.nextLine();
System.out.println("Enter your bank's threshold");
int threshold=input.nextInt();
System.out.println("Enter the smaller interest");
double small_interest=input.nextDouble();
System.out.println("Enter tht larger interest");
double large_interest=input.nextDouble();
System.out.println("How much do you want to deposit?");
original_amount=input.nextDouble();
System.out.println("How many years do you want the program to trace?");
int trace=input.nextInt();
double effective_interest=0;
if (original_amount>=threshold){
effective_interest=(large_interest);}
else if (original_amount<threshold){
effective_interest=(small_interest);}
double amount_gained=((original_amount * (effective_interest/100)));
double yearly_amount=original_amount+amount_gained;
    int x=1;
    int year=1;
    System.out.println("Report on "+name+"'s savings account :");
    System.out.println("Original Amount "+ original_amount);
     System.out.println("");
     while (x<=trace)
    {
      System.out.println("Year"+year+":");
      System.out.println("Effective interest rate "+effective_interest+"%");
      System.out.println("Amount gained "+amount_gained);
      System.out.println("Amount at the end of the year "+(yearly_amount));
      System.out.println("");
      x++;
      year++;
    }
    original_amount+=amount_gained;
  }
}

2 个答案:

答案 0 :(得分:1)

对于循环的每次迭代,您应该进行更新信息所需的计算。现在你只打印,只更新变量年份。尝试将一些计算放在while循环中。

<强>更新
original_amount + = amount_gained;不在while循环中。试着把它放在那里。

while (x<=trace)
    {
      System.out.println("Year"+year+":");
      System.out.println("Effective interest rate "+effective_interest+"%");
      System.out.println("Amount gained "+amount_gained);
      System.out.println("Amount at the end of the year "+(yearly_amount));
      System.out.println("");
      original_amount+=amount_gained;
      x++;
      year++;
    }

答案 1 :(得分:1)

还想指出,x和年份都是不必要的,因为它们完全相同。