I am learning constructor and objects and method on Java language. I understand the difference between non-argument and parameter constructor but I encounter a problem on my code that I can't seem to figure out.
I am writing a code for capturing the registration information. I create a class CompetitionEntry
and inside the class, I insert 2 private attributes as private String projecTitle;
and private int teamSize;
and along with one class attribute as double feePerParticipant = 6.50;
with the initial value of $6.50.
Then I create a no-argument constructor that I have initializes as projectTitle = "N/A";
and teamSize = 0;
. An overloading constructor that initializes the attributes using the incoming arguments.
And I create the Mutator and Accessor method for the attribute teamSize but I want to ensure that it only except positive value. Lastly i create the method call computeTeamFee()
that return the total fees by multiplying teamSize with feePerParticipant.
I wanted my code to get an output for the total team fee from the computeTeamFee();
method but I can't seem to find the problem and I need to initialize the object (using constructor) with the values "Super Tech" for the title and team size is 5.
And I can only change from the objects method to change the values and display the output.
Please help me. I'm getting more and more confused.
public class CompetitionEntry {
private String projectTitle;
private int teamSize;
double feePerParticipant = 6.50;
public CompetitionEntry () {
this.projectTitle = "N/A";
this.teamSize = 0;
}
public void setTeamSize(int teamSize) {
//This part i not to sure how to read only positive value.
if (this.teamSize <= 0) {
System.out.println ("Negative value are not acceptable.")
}
else {
this.teamSize = teamSize;
}
}
public int getTeamSize() {
return teamSize;
}
public double computeTeamFee() {
double totalFee;
totalFee = this.teamSize * feePerParticipant;
return totalFee;
}
public static void main(String[] args) {
CompetitionEntry obj = new CompetitionEntry ("Super Tech","5");
System.out.println("Title: " + obj.projectTitle);
System.out.println("Team Size: " + obj.teamSize);
}
}
When you create the CompetitionEntry object, you are giving it the parameters "Super Tech" and "5" as inputs.
CompetitionEntry obj = new CompetitionEntry ("Super Tech", 5);
//P.S You put "5" instead of 5 (remove the quotations for integer
//values as its not a string) as shown above
These input parameters for obj ("Super Tech" and "5") correspond with the inputs to the constructor (title and size)
public CompetitionEntry (String title, int size) {
this.projectTitle = title;
this.teamSize = size;
}
The constructor then sets projectTitle and teamSize to be equal to the inputs that went into the constructor.
There are some other mistakes in your codes such as missing a semi-colon in your setTeamSize function for the System.out.print line.