I hit a bump when I\'m doing my Java code. I feel like I somehow got the concept messed up, like I not sure for this:
void setScore(float[] sco)
{
sco = scor
You are assigning a value of the class variable score
to the parameter sco
when you should do the opposite. In other words:
Your code says:
sco = score;
But what you should do is:
score = sco;
In both functions you need to switch the order of score
and sco
so that score
gets the value of sco
.
As far as your error, in setScore(float sco, int id)
you defined parameter sco
as a float
but you are trying to access it as an array (by saying sco[Id] = score
). That is why you are getting your error message.
The type of the expression must be an array type but it resolved to float
Like I said, you can fix this by switching the order again:
sco[Id] = score;
Into:
score[Id] = sco;
EDIT:
As far as this part:
I'm confused what I should put in the bracket, the book asks me to put "float[] score" > instead of "float[] sco", but it doesn't work, so I edited a bit after several trials. This > part of coding generally describes the method of overloading that stores the score for 5 > subjects.
Since you wanted to know how to use the same names for parameters and class variables, as @Smutje mentioned, you should use the keyword this
.
That way, there is no ambiguity with which score
you are using:
this.score
belongs to your class called Score
and can be used in any function inside the class. It is visible to everything inside the class.
score
is a function parameter local to a function setScore()
and can only be used inside setScore()
. It is only visible inside the function.
Therefore, including everything mentioned, you should make the following changes:
Change:
public void setScore(float sco, int id)
{
sco[id] = score;
}
void setScore(float[] sco)
{
sco = score;
}
To:
public void setScore(float score, int id) // changed sco to score
{
this.score[id] = score; // switched order, added keyword this
}
void setScore(float[] score) // changed sco to score
{
this.score = score; // switched order, added keyword this
}
I guess you mixed up the variable names:
void setScore(float[] sco)
{
sco = score;
}
public void setScore(float sco, int id)
{
sco[id] = score;
}
because score
is the field which you want to populate and sco
is the parameter which you want to populate score
with. The code above does not change any contents of Score
, so try to swap it to
void setScore(float[] sco)
{
this.score = sco;
}
public void setScore(float sco, int id)
{
this.score[id] = sco;
}
it also would have helped if you have started using this
to mark instance fields explicitly.
Check again how you set your score:
void setScore(float[] sco)
{
sco = score;
}
What is sco
? What you want to assign to what?
You are assigning your local variable to the parameter. It should be the other way around.
(this.score = sco)