A memory address is returned instead of the returned class name
I try to get the two teams to play each other. I call this when I say team1.play (team2); when I generate a number less than 0.5, team2 should win, and if it is more than 0.5, then team 1 should win. when team 1 wins it displays correctly as knicks, but when team 2 wins it displays the memory address. how can I get it to correctly say that the networks are winning and not the team @ 78987neu73
public class teams{
public static void main(String [] argv){
team team1 = new team("knicks");
team team2 = new team("nets");
team1.lose();
team2.win();
team2.lose();
team2.printrecord();
team1.play(team2);
}//main
}//teams
class team{
int wins;
int losses;
String name;
public team(String n){
name = n;
wins = losses = 0;
}//constructor
public void lose(){
losses++;
}//losses
public void win(){
wins++;
}//wins
public void printrecord(){
System.out.println("W-L: " +wins+"-"+losses);
}
public void play(team j){
if((Math.random())<0.5){
System.out.println("The "+j+" Have Won!");
}//if
else
System.out.println("The "+name+" Have Won!");
}
}
source to share
There are many ways to solve your problem, the simplest would be to get the command name j
like this:
if((Math.random())<0.5){
System.out.println("The "+j.name+" Have Won!"); //You should use the name of the j team
}
else {
System.out.println("The "+name+" Have Won!");
}
Another option is to override the method toString()
in your class team
.
public String toString() {
return name;
}
If you want to be more advanced and follow industry standards, then let's build the class correctly team
:
class Team { //class names are PascalCase
private int wins; //encapsulate fields
private int losses;
private String name;
//constructor
public Team(String n) {
name = n;
wins = losses = 0;
}
//getter and setter methods
public int getWins() {
return wins;
}
public void setWins(int wins) {
this.wins = wins;
}
public int getLosses() {
return losses;
}
public void setLosses(int losses) {
this.losses = losses;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void lose() {
setLosses(getLosses() + 1);
}
public void win() {
setWins(getWins() + 1);
}
public void printrecord() {
System.out.println("W-L: " + getWins() + "-" + getLosses());
}
public void play(Team otherTeam) { //more descriptive name
if ((Math.random()) < 0.5) {
System.out.println("The " + otherTeam.getName() + " Have Won!");
}
else {
System.out.println("The " + this.getName() + " Have Won!");
}
}
}
source to share
Override toString()
in team
, here's an example
@Override
public String toString(){
return String.format("%s W-L: %d-%d",name, wins, losses);
}
this way yours play(team j)
can print team j
. In addition, the Java naming convention has classes that start with a capital letter. team
should be team
.
source to share