Java - 如何随时间添加数字?

时间:2016-03-30 22:15:29

标签: java

<pre> import java.util.*;

public class Test {
private static int StartingMoney = 1000;
private static int MaxMoney = 10000;
private static int Add = 100;
static Scanner question = new Scanner(System.in);
    public static void main(String[] args) {
        while(StartingMoney != MaxMoney){
            System.out.println("1:Add Money");
            int userInput = question.nextInt();
                if(userInput == 1){
                    System.out.println(StartingMoney + Add);
                }

        }
    }

}
 <code>

此代码的目标是添加一个数字,直到达到一定数量,并且用户将能够选择他或她是否可以将数字添加到他们当前的数量。输出总是1100

1 个答案:

答案 0 :(得分:10)

通过执行System.out.println(StartingMoney + Add);,您只需将值打印到控制台,而不是更改实际的StartingMoney变量,这仍然是1000

您的程序将无限循环,因为永远不会达到条件StartingMoney != MaxMoney

你应该这样做:

StartingMoney += Add;
System.out.println(StartingMoney);

以下是更正后的代码段:

import java.util.*;

public class Test {
    private static int StartingMoney = 1000;
    private static int MaxMoney = 10000;
    private static int Add = 100;
    private static Scanner question = new Scanner(System.in);

    public static void main(String[] args) {
        while(StartingMoney != MaxMoney){
            System.out.println("1: Add Money");
            int userInput = question.nextInt();
            if(userInput == 1) {
                /* Note the change here */
                StartingMoney += Add;
                System.out.println(StartingMoney);
            }
        }
    }
}