Im trying to rolling dices and then system print 1 of the dices when im calling slaTarningar() inside class Player,
class Player{
int armees = 0;
int diceAmount = 0;
Dice Dices[];
Player(String playerType){
armees = 10;
diceAmount = ("A".equals(playerType)) ? 3 : 2;
Dices= new Dice[diceAmount];
for(int i=0;i<Dices.length;i++){
Dices[i]=new Dice();
}
}
void slaTarningar(){
for(int i=0;i<Dices.length;i++){
Dices[i].role();
}
开发者_如何学C System.out.println ("Dice: "+ Dices[1]);
}
void visaTarningar(){
String allDices="";
for(int i=0;i<Dices.length;i++){
allDices += ", " + Dices[i];
}
}
}
class Dice{
int value;
Dice(){
value=0;
}
void role(){
int role;
role = (int)(Math.random()*6+1);
value=role;
}
}
All i get is my project name, and something weird else:
Dice: javaapplication9.Dice@9304b1
What is wrong here?
You need to add a toString
method to Dice
:
class Dice{
int value;
Dice(){
value=0;
}
void role(){
int role;
role = (int)(Math.random()*6+1);
value=role;
}
public String toString() {
return "" + value + "";
}
}
Or add a getValue
method:
class Dice{
int value;
Dice(){
value=0;
}
void role(){
int role;
role = (int)(Math.random()*6+1);
value=role;
}
public int getValue() {
return value;
}
}
//.. in other class:
System.out.println ("Dice: "+ Dices[1].getValue());
You're printing the object, not the value. Use
System.out.println ("Dice: "+ Dices[1]*.value*);
or you can add a toString() method to the Dice class.
class Dice{
int value;
Dice(){
value=0;
}
void role(){
int role;
role = (int)(Math.random()*6+1);
value=role;
}
@Override
public String toString() {
return value + "";
}
}
You need to tell Java how to print a Dice object - otherwise it uses an internal representation (the object's class and its hash code) from Object.toString()
You need to add a "toString" method to your Dice class.
You need to override Dice.toString()
Your argument to the println
method is "Dice: "+ Dices[1]
.
The +
operator can concatenate a String with an arbitrary object, which it does by converting the object into a String first. It's able to do this because of the existence of the Object.toString()
instance method, which returns a string representation of any object.
That's what's being called here to convert Dice[1]
into a string constant (what you see is the default implementation of toString()
that's inherited from Object
).
So, you have two options to resolve this:
- Override
public String toString()
on yourDice
class. Be aware that this will be the default "string representation" of instances of your class anywhere that they're output as text, so choose something that makes sense in a general context. Or: - Explicitly pass the value of the
Dice
reference into the println statement. Something likeprintln("Dice: " + Dices[1].value)
.
精彩评论