仅当用户输入键时如何使计数器加1

时间:2018-08-17 14:56:24

标签: java

System.out.println("Do you want to add 1? if yes type in '0.01' ");

问题是它只能运行一次。我试图将其添加到while循环(while(i> 100))中,但它只是打印到100,直到再次询问用户为止。

我的代码:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        int i = 0;
        double yes = 0.01;

        System.out.println("i = " + i);
        System.out.println("Do you want to add 1? if yes type in '0.01' ");

        Scanner keyboardInput = new Scanner(System.in);
        double add = keyboardInput.nextDouble();

        if (yes == add) {
            i++;
            System.out.println("i now is: " + i);
       }
    }

}

1 个答案:

答案 0 :(得分:0)

while(i < 100)而不是while(i > 100)

这很好:

public static void main(String[] args) {
    int i = 0;
    double yes = 0.01;

    while(i < 100) {
        System.out.println("i = " + i);
        System.out.println("Do you want to add 1? if yes type in '0.01' ");

        Scanner keyboardInput = new Scanner(System.in);
        double add = keyboardInput.nextDouble();

        if (yes == add) {
            i++;
            System.out.println("i now is: " + i);
        }
    }
}