不公平的糖果分销

时间:2016-04-26 23:09:22

标签: java class logic

我正在完成一项任务,并且很难找出使程序运行的逻辑需求。我不想直接回答,但有人能指出我正确的方向吗?

分配: 定义一个名为UnfairCandyDistributor的类。 UnfairCandyDistributor对象代表一个卑鄙的大哥,他将在他和他饥饿的小弟弟之间分配一组糖果。这将是不公平的:对于给予兄弟姐妹的每一颗糖,大哥为自己带来了一些额外的糖果,等于兄弟姐妹的总数。每个UnfairCandyDistributor对象应该具有相同的方法: public void nextCandy() 每次调用nextCandy时,该方法都会打印一条关于谁获得糖果的消息。每次调用nextCandy都会产生一行输出。这次输出如下:

public class TestCandy2 {
    public static void main(String[] args) {
        UnfairCandyDistributor mean = new UnfairCandyDistributor();
        mean.nextCandy();        // 1 for you.
        mean.nextCandy();        // 1 for me.
        mean.nextCandy();        // 2 for you.
        mean.nextCandy();        // 1 for me.
        mean.nextCandy();        // 2 for me.
        mean.nextCandy();        // 3 for you.
        mean.nextCandy();        // 1 for me.
        mean.nextCandy();        // 2 for me.
        mean.nextCandy();        // 3 for me.

这是我到目前为止所做的课程:

public class UnfairCandyDistributor {

    private int you;
    private int me;
    private int extra;


    public void nextCandy()
    {

        if (you != me || extra != you - 1)
        {
            me++;
            System.out.println(me + " for me");
        }
        else
        {
                 you++;
                 System.out.println(you + " for you");
            extra = 0;
        }
  }
}

1 个答案:

答案 0 :(得分:0)

难道你不能只添加一个布尔变量来告诉你将糖果送到谁?

public class UnfairCandyDistributor {

    private int you = 0;
    private int me = 0;
    private boolean candyToMe = false;

    public void nextCandy()
    {
        if (candyToMe)
        {
            for (int i=0; i<you; i++) {
                 System.out.println("one for me");
                 me++;
        }
        else
        {
                 System.out.println("one for you");
                 you++;
        }
        candyToMe = !candyToMe;
    } 
}

public class UnfairCandyDistributor {

    private int you = 0;
    private int me = 0;
    private boolean candyToMe = false;

    public void nextCandy()
    {
        if (candyToMe)
        {
                 System.out.println(you + " for me");
                 me += you;
        }
        else
        {
                 System.out.println("1 for you");
                 you++;
        }
        candyToMe = !candyToMe;
    } 
}

..取决于您是否希望糖果一次一个地发出或在适当的情况下手工制作。