如何打印剩余的优惠券数量

时间:2014-05-02 02:05:34

标签: java loops

我正在编写一个编程项目。我的项目是关于用户输入钱购买他们想要消费的巧克力棒的数量。每个巧克力棒包含1张优惠券。 1巧克力等于1美元。兑换6张优惠券将获得用户1个免费酒吧以及免费酒吧的额外优惠券。例如,如果用户输入6 $,则用户将获得6个酒吧兑换6个优惠券将获得免费酒吧,因此免费酒吧将具有优惠券,因此用户剩下一个优惠券。我必须在用户之后打印剩余的优惠券数量赎回它。

我用这个等式得到剩余的优惠券

amount = coupons / 6;

当我运行我的代码时,如果我购买6个巧克力棒,则金额打印0而不是剩余的剩余剩余物,如1张优惠券。请帮助我做错了什么。 继承我的代码

import java.util.Scanner;
public class Chp4PP16RedeemChocolateCoupons_John {

public static void main(String[] args) 
{
    //Instance Variables
    int CostOfBar = 1;
    int ChocolateBar = 0;
    int UserDollar = 0;
    int Amount;
    int Coupons = 0;
    int Total = 0;

    Scanner keyboard = new Scanner(System.in);
    //Tell the user how many chocolate bars they want to buy
    System.out.println("Welcome User,\nPlease enter your money to buy the amount of chocolate bars you want.\nChocolate Bar = $" + CostOfBar);
    UserDollar = keyboard.nextInt();

    System.out.println("You have entered $" + UserDollar+ "\n");
    System.out.println("You have decided to buy");
    System.out.println((Amount = UserDollar + ChocolateBar) + " Chocolate Bars.");


    //get total amount and remainder of coupons
    while (Coupons > 6)
    {
        Total = Amount / 6;
    }
    System.out.println("\nYou have " + Total + " remaining coupons.");


}

}

1 个答案:

答案 0 :(得分:0)

正如您对帖子的评论所述,您的while循环将是无限的,因为条件是ChocolateBars> 6,永远不会是假的。此外,循环内的代码将继续除以6,这根本不是你想要的。我想你需要了解modulus division

这应该适合你:

Coupons = ChocolateBar;
//now Coupons contains the total amount of coupons the user will have gained
 do {
    Total = Coupons % 6; //Here we use modulo to make the total left be the remainder of the amount of coupons divided by 6        
    Total += Coupons / 6; //Add on the amount of coupons redeemed in the free chocolate bars 
    Coupons = Total;
} while (Coupons >= 6);
System.out.println("\nYou have " + Total + " remaining coupons.");

编辑:还意识到您需要确定计算购买的巧克力数量。这条线需要改变:

System.out.println((Amount = UserDollar + ChocolateBar) + " Chocolate Bars.");

这样的事情:

ChocolateBar = UserDollar/CostOfBar;
System.out.println(ChocolateBar + " Chocolate Bars.");