Reputation: 18103
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();
}
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?
Upvotes: 0
Views: 1322
Reputation: 38511
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()
Upvotes: 1
Reputation: 146302
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());
Upvotes: 1
Reputation: 9278
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.
Upvotes: 1
Reputation: 103777
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:
public String toString()
on your Dice
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:Dice
reference into the println statement. Something like println("Dice: " + Dices[1].value)
.Upvotes: 0