我正试图让两支球队相互比赛。当我说team1.play(team2)时我称之为; 当我生成一个小于0.5的数字时,team2应该获胜,如果它大于0.5,那么第1队应该获胜。当1队获胜时,它会正确显示为尼克斯,但是当team2获胜时,它会显示内存地址。我如何能够正确地说网队赢了而不是球队@ 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!");
}
}
答案 0 :(得分:5)
您的team
班级
public String getName() {
return name;
}
public void play(team j){
if((Math.random())<0.5){
System.out.println("The "+j.getName()+" Have Won!");
}//if
else
System.out.println("The "+name+" Have Won!");
}
答案 1 :(得分:4)
您已直接放置j
。尝试使用以下代码
public void play(team j){
if((Math.random())<0.5){
System.out.println("The "+j.name+" Have Won!");
}//if
else
System.out.println("The "+this.name+" Have Won!");
}
答案 2 :(得分:3)
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!");
}
在这里,“j”是一个对象,而不是一个字符串。使用j.name而不是j。
答案 3 :(得分:3)
有很多方法可以解决您的问题,最简单的方法是直接获取j
团队的名称:
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!");
}
另一种方法是覆盖toString()
类中的team
方法。
public String toString() {
return name;
}
如果您想更加先进并遵循行业标准,那么让我们正确构建您的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!");
}
}
}
答案 4 :(得分:3)
在toString()
中覆盖team
,这是一个示例
@Override
public String toString(){
return String.format("%s W-L: %d-%d",name, wins, losses);
}
这样play(team j)
可以打印team j
。此外,Java命名约定的类以大写字母开头。 team
应为Team
。
答案 5 :(得分:1)
您需要做的就是覆盖您的团队类中的toString功能以返回名称...
只需在团队课程中添加此代码即可。
@Override
public String toString() {
return name;
}