The task I'm attempting to solve is part of a school assignment. I've already solved it one way - yet that solution is rather ugly - so I'm attempting to solve it another way.
The task requires me to create a new class PairOfDice that creates two Dice objects, rolls them, checks if they're a pair, and then writes the result. I'm trying to have the PairOfDice class create two Dice classes that roll themselves, save their value to themselves, and I then have the PairOfDice class check if they rolled a pair, and lastly write out the result. Yet when I attempt to have the PairOfDice class create two Dice objects, they are created with a wrong number of sides (value), yet I don't understand why.
I've attempted to search this forum, and the Internet, yet I still don't understand what the error is - would you please help me?
EDIT: I've done some debugging - when I run:
dice01 gets the value:
dice01 Dice(6, 2) Dice
which I assume has something to do with toString - does it automatically rewrite dice01's value when it's created?
I suggest you avoid Math.random(). I know the Java® Tutorial say it is more convenient than a Random instance, but I am not convinced. Using the nextInt method is more robust than the (int) cast.You should mark all method called from the constructor private or final; there is some discussion about that problem here.
Never write == true or == false. Not
if (b == true) ... but if (b) ... Not
if (b == false) ... but if (!b) ... Using == is error‑prone; we see people who write = by mistake.
if (...) return true; else return false; You should writeYou can simplify the method which returns the arrayNow you no longer need the array field at all.
What you are getting back from the printing call is determined by the toString method which you wrote. It is confusing because you don't say what the numbers mean. If you wrote this as your toString method, it would be easier to understand:-That will give a very similar output to
"A " + nsides + "-sided die showing " + value + "."