繁体   English   中英

为什么我的 while 循环每次都打印出相同的内容?

[英]Why is my while loop printing out the same thing each time?

对不起,我知道这个问题每天可能会被问一百万次,但我真的找不到我正在寻找的答案。 我是 Java 的初学者(我正在上大学,正在学习一堆新语言),我的 while 循环每次都打印出同样的东西。

import java.util.Scanner;

public class Main
{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("What is the loan amount? ");
        int amount = scanner.nextInt();
        int x = 1;
        //your code goes here
        while (x < 6){
            System.out.println("Month " +x+ ":");

            int percent = (amount / 10);
            System.out.println("Payment: 10 percent of " +amount+ " = " +percent);

            int rAmt = amount - percent;
            System.out.println("Remaining amount: " +rAmt);

            x++;
        }
    }
}

所以问题是,在 while 循环中进行计算后,您永远不会真正改变amount 我认为你想要做的是设置amount = rAmt; ,这将产生以下代码。 这将导致每次迭代减少 10% 的数量,并将这个新值结转。

...
//your code goes here
        while (x < 6){
            System.out.println("Month " +x+ ":");

            int percent = (amount / 10);
            System.out.println("Payment: 10 percent of " +amount+ " = " +percent);

            int rAmt = amount - percent;
            System.out.println("Remaining amount: " +rAmt);
            amount = rAmt; 
            x++;
        }
...

暂无
暂无

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

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