代码不生成输出java

时间:2015-10-20 13:43:32

标签: java printing

我试图为每个月编写一个计算CD值的代码。 假设您将 10,000 美元放入CD中,年收益率 6,15%。 一个月后CD值得:

10000 + 10000 * 6,15 / 1200 = 10051.25

下个月之后:

10051.25 + 10051.25 * 6,15 / 1200 = 10102.76

现在我需要显示用户输入的特定月数的所有结果, 所以

month1 =

month2 =

但是我写的这段代码没有打印出来。 你能看出什么是错的吗?

提前致谢!

import java.util.Scanner;

public class CDValue {
public static void main(String[] args){
    Scanner input = new Scanner(System.in);

    System.out.println("Enter an amount");
    double amount = input.nextInt();

    System.out.println ("Enter the annual percentage yield");
    double percentage = input.nextDouble();

    System.out.println ("Enter the number of months");
    int months = input.nextInt();

    double worth = amount + amount * percentage / 1200;

    for (int i = 1; i < months; i++) {

        while (i != months) {
            amount = worth;

            worth = amount + amount * percentage / 1200;


        }
    System.out.print(worth); 

5 个答案:

答案 0 :(得分:1)

您不会在

中修改imonths
while (i != months) {
    ....
}

因此,如果满足(i != months)条件,则循环将永远运行,并且您永远不会进入System.out.print语句。

答案 1 :(得分:0)

for (int i = 1; i < months; i++) {

while (i != months) {
//you have to modify i or to modify the while condition.
}

如果您在无法退出循环的情况下不修改i

答案 2 :(得分:0)

更正代码 -

import java.util.Scanner;

public class CDValue {
public static void main(String[] args){
Scanner input = new Scanner(System.in);

System.out.println("Enter an amount");
double amount = input.nextInt();

System.out.println ("Enter the annual percentage yield");
double percentage = input.nextDouble();

System.out.println ("Enter the number of months");
int months = input.nextInt();

double worth = amount + amount * percentage / 1200;

for (int i = 1; i <= months; i++)
{
System.out.print("Month " + i + " = " + worth);
amount = worth;
worth = amount + amount * percentage / 1200;
}

注意:如果要打印每个月的值,则print语句应位于循环内。对于上面提到的目标,您不需要两个循环。

答案 3 :(得分:0)

正如您所知,如果您不修改代码,您的代码将无法退出while循环。只需删除while循环。你的代码应该是这样的:

import java.util.Scanner;

public class CDValue {
public static void main(String[] args){
Scanner input = new Scanner(System.in);

System.out.println("Enter an amount");
double amount = input.nextDouble();

System.out.println ("Enter the annual percentage yield");
double percentage = input.nextDouble();

System.out.println ("Enter the number of months");
int months = input.nextInt();

double worth = amount + amount * percentage / 1200;

for (int i = 1; i < months; i++) {
amount = worth;
worth = amount + amount * percentage / 1200;
}
System.out.print(worth);
}
}

答案 4 :(得分:0)

谢谢!通过使用解决它     {     System.out.print(&#34;月&#34; + i +&#34; =&#34; +值得);     金额=值;     价值=金额+金额*百分比/ 1200;

而不是while循环。 它现在有效:)非常感谢!