繁体   English   中英

代码不产生输出Java

[英]Code produces no output java

我试图每月编写一个代码,计算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); 

您既不会修改i也不会修改months

while (i != months) {
    ....
}

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

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

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

如果您不修改i而又无法退出循环

更正的代码-

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语句应位于循环内。 对于上面提到的目标,您不需要两个循环。

如您所知,如果不进行修改,您的代码将不会退出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);
}
}

谢谢! 通过使用{System.out.print(“ Month” + i +“ =” + worth);来解决 金额=价值; 价值=金额+金额*百分比/ 1200;

而不是while循环。 现在可以正常工作了:)非常感谢!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM