need help with constructors, accessors, and mutators. Firstly, do I need a void
ID: 3711511 • Letter: N
Question
need help with constructors, accessors, and mutators.
Firstly, do I need a void return type stated in the constructor method?
Secondly, when I make a new class called testGame, I am receiving an error after calling the setHomeScore and getHomeScore methods. Also, the I'm not sure if I did the toString method correctly.
here is the code for the Game class.
public class Game
{
private int homeScore;
private int visScore;
private String homeTeam;
private String visTeam;
public void constructGame(int hScore, int vScore, String hTeam, String vTeam)
{
homeScore = hScore;
visScore = vScore;
homeTeam = hTeam;
visTeam = vTeam;
}
public int getHomeScore()
{
return homeScore;
}
public int getVisScore()
{
return visScore;
}
public void setHomeScore(int point)
{
homeScore += point;
}
public void setVisScore(int point)
{
visScore += point;
}
public String toString()
{
if (homeScore > visScore)
return homeTeam + " " + homeScore + " " + visTeam + " " + visScore;
return visTeam + " " + visScore + " " + homeTeam + " " + homeScore;
}
}
Also, here (easier to read): https://pastebin.com/geFEdUGR
Here is the code for the testGame class.
public class testGame {
public static void main(String[] args)
{
Game test = new Game();
test.setHomeScore(5);
System.out.println(test.getHomeScore());
System.out.println(toString());
}
}
**** When I call toString in main I get the following error: java: non-static method toString() cannot be referenced from a static context
Explanation / Answer
Firstly, do I need a void return type stated in the constructor method?
Since this is method and not a constructor it needs an return type and since it doesnt return anything so its void.constructGame is simply yet another member function and wont be called during object creation.
if you want to create a constructor then below is the syntax
public Game(int homeScore, int visScore, String homeTeam, String visTeam) {
super();
this.homeScore = homeScore;
this.visScore = visScore;
this.homeTeam = homeTeam;
this.visTeam = visTeam;
}
Secondly, when I make a new class called testGame, I am receiving an error after calling the setHomeScore and getHomeScore methods.
I tested your code and no error occured.
Also, the I'm not sure if I did the toString method correctly.
toString is not a static method so outside of the Class Game you called call it directly with out object. Since you have created object test for Class Game it should be called test.toString();
Game test = new Game();
test.setHomeScore(5);
System.out.println(test.getHomeScore());
System.out.println(test.toString());
OUTPUT OF YOUR CODE
5
null 5
null 0
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.