Preface- I'm an A level computer science student, and for the most part it's a pretty easy subject. We are graded based on a written test, a programming assignment, and a programming test where we are given pre-written code and asked to modify it.
As homework I was given an old piece of exam code, with the homework being to go through and add comments as to what the code is for.
This is easy to do, as the code is just for a text based noughts and crosses game.
Most of the code isn't too bad (Some of the exam board code is seriously questionable), however the method for choosing which player goes first is a bit strange-
char getWhoStarts() {
char whoStarts;
int randomNo;
Random objRandom = new Random();
randomNo = objRandom.nextInt(100);
if (randomNo % 2 == 0) {
whoStarts = 'X';
} else {
whoStarts = 'O';
}
return whoStarts;
}
Obviously, this method works, but I don't really understand why someone would ever generate a random integer, and then check if it is even, when all they want is an evenly weighted random. I could understand if this method had more than two return possibilities, or needed to be weighted, however in this case it makes no sense.
I would replace it with this -
char getWhoStarts() {
Random r = new Random();
if(r.nextBoolean()) {
return 'X';
} else {
return 'O';
}
}
Also, the boolean could probably be a global variable, rather than being initialised each time the method is called.
Could someone explain to me, if there is a reason to do this, what is that reason? And are there any benefits of a random integer rather than a random boolean.
Thanks.
Aucun commentaire:
Enregistrer un commentaire