while循环有问题,没有得到预期的输出?

时间:2018-09-19 09:56:36

标签: java while-loop

这是一个Java问题,我的while循环有问题。该程序必须允许客户输入他们想购买的汽油升数,升值为$ 1.75。然后,对于每个 升汽油至客户输入的数量,程序必须显示 总计。

这是预期的输出,我没有得到

Please Enter the Litres of Petrol (a whole number): 20
Litre 0: $0.0
Litre 1: $1.75
Litre 2: $3.5
...
Litre 19: $33.25
Litre 20: $35.0 

这是我到目前为止的代码。

public static void main(String[] args) {
    Scanner kb = new Scanner(System. in );
    int numOfLiter;

    System.out.println("Please enter the liters of Petrol: ");
    numOfLiter = kb.nextInt();

    double pricePerLitre = 1.75;
    int count = 0;

    while (count <= 10) {
        Double total = pricePerLitre + count;
        System.out.println("Liter " + count + ": " + total);

        count++;

    }
}

4 个答案:

答案 0 :(得分:2)

根据您的输出,您的while循环应循环运行,直到提供输入,即if(isMobile.any())

  $(document).ready(function(){
       if(!isMobile.any()) {
             $('.hero-slider').slick({ /* slider code here */ });
       }
    });

还有

numOfLiter

应该是

int count = 0;

while (count <= numOfLiter) {
    Double total = pricePerLitre * count;
    System.out.println("Liter " + count + ": " + total);

    count++;
}

答案 1 :(得分:1)

您可以使用简单的for-loop来实现相同的目的。

public static void main(String[] args) {
    Scanner kb = new Scanner(System. in );
    int numOfLiter;

    System.out.println("Please enter the liters of Petrol: ");
    numOfLiter = kb.nextInt();

    double pricePerLitre = 1.75;

    for (int i = 0; i <= numOfLiter; i++) {
        Double total = pricePerLitre * i;
        System.out.println("Liter " + i + ": " + total);
    }
}

答案 2 :(得分:0)

尝试

Double total = pricePerLitre * count; 

而不是:

Double total = pricePerLitre + count;

在您的代码中。

答案 3 :(得分:0)

public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    System.out.println("Please enter the liters of Petrol: ");
    int numOfLiter = kb.nextInt();
    double pricePerLitre = 1.75;
    IntStream.range(0, numOfLiter + 1).forEach(i ->  System.out.println("Liter " + i  + ": " + i* pricePerLitre));
}

但是在实际代码中最好使用BigDecimal