jeudi 27 juillet 2017

Why one of the cases is always unreachable?

Why the output of the following code is always suck. How to get happy as the output? Why the happy branch is unreachable?

public class HowToMakeStackoverflowBetter {

    private static final int HUMAN_PATIENCE = 10;
    private List<Member> members = new ArrayList<>();
    private int atmosphere = -10;
    private Random r = new Random();
    public HowToMakeStackoverflowBetter(int size) {
        for (int i = 0; i < size; i++) { members.add(new Member()); }
    }
    public Member pick() { return members.get(r.nextInt(members.size())); }

    public class Member {
        private int patience = HUMAN_PATIENCE;
        private Question question = null;
        public Member() { patience = r.nextInt(patience+1) + atmosphere; }
        public void vote(Question q) {
            if (patience >= 0) {
                voteUp(q);
            } else {
                voteDown(q);
            }
        }
        public void ask() {
            question = new Question();
            for (Member member : members) {
                member.vote(question);
            }
        }
        private void voteUp(Question q) { ++q.vote; }
        private void voteDown(Question q) { --q.vote; }
        public String toString() {
            return (question.vote >= 0)? "Happy!" : "Suck!";
        }
    }

    public class Question { private int vote; }

    public static void main(String[] args) {
        HowToMakeStackoverflowBetter stackoverflow = new HowToMakeStackoverflowBetter(100);
        Member me = stackoverflow.pick();
        me.ask();
        System.out.println(me);
    }
}

After a 1000 times loop, it gives us 1000 sucks. I remember 2 or 3 years ago, this was not the case. Something changed?

If you can only change one line in the above code, how to get happy :)?

Aucun commentaire:

Enregistrer un commentaire