簡體   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