Java收银机程序

时间:2019-02-27 11:46:14

标签: java for-loop

我必须写一个收银机程序。该程序如下所示:

收银机程序。请给物品价格,停止输入0。 459 315 1125 3456 396 0 总和5751 Ft。 平均1150,20英尺 最昂贵的3456英尺 最昂贵的是200,47%,比平均价格贵。 总共比300英尺便宜3项。

    Scanner sc = new Scanner(System.in);
    double average = 0;
    int sum = 0;
    int mostExpensive = 0;
    int smaller500 = 0;
    System.out.println("Cash register program, please give prices, stops when 0 entered");
    int prices = sc.nextInt();
    sum += prices;

    for (double i=1; prices != 0; i++)
    {
        prices = sc.nextInt();
        if (prices < 500)
        {
            smaller500++;
        }
        sum += prices;
        average = i;
        if (prices > mostExpensive )
        {
            mostExpensive = prices;
        }

    }
    System.out.println("Total amount "+sum+" Ft.");
    System.out.printf("Average is %.2f Ft. %n",sum/average);
    System.out.println("Most expensive is "+mostExpensive+" Ft.");
    System.out.printf("The most expensive is %.2f%% expensive then the average.%n",(mostExpensive/(sum/atlag))*100-100);
    System.out.println("Totally "+smaller500+" pcs. cheaper then 500 FT.");
}

}

程序有什么问题?如果我只给出一件商品,那么给出多少数字都没关系,它说一件商品比500英尺便宜。

1 个答案:

答案 0 :(得分:1)

如果您为prices输入零,则应该退出循环。但是在此之前,所有这些代码都将运行:

    prices = sc.nextInt();
    if (prices < 500)
    {
        smaller500++;
    }
    sum += prices;
    average = i;
    if (prices > mostExpensive )
    {
        mostExpensive = prices;
    }

(除其他事项外),它将使变量smaller500递增。

您可以将循环更改为在末尾而不是开始输入prices,因此将立即检查循环条件;或者您可以在输入零时跳出循环。

for (double i=1; prices != 0; i++)
{
    prices = sc.nextInt();
    if (prices == 0) {
        break;
    }
    if (prices < 500)
    {
        smaller500++;
    }
    sum += prices;
    average = i;
    if (prices > mostExpensive )
    {
        mostExpensive = prices;
    }
}