Reputation: 395
I was trying to create a program that had multiple characters with different attributes. I ran into an issue calling a method I (tried) to define in Class Character.
public class CharacterAttributes
{
public static void main(String[] args)
{
Character John = new Character("John", 0);
workout(5);
}
}
class Character
{
private String name;
private int Str;
public Character(String n, int initialStr)
{
name = n;
Str = initialStr;
}
public void workout(int byAmt) {
Str = Str + byAmt;
}
}
The compiler said the "workout()" method could not be resolved.
Thanks!
There's probably a lot of errors, honestly.
Upvotes: 1
Views: 7711
Reputation: 519
You can't just do workout(5)
you did this
Character John = new Character("John, 0);
so you do:
John.workout(5)
and sorry but your conventions are pretty bad
public int Str
should be public int str
Upvotes: 0
Reputation: 72884
The method belongs to class Character
, so you should call it against the instance John
:
John.workout(5);
As a side note, it is conventional to start the name of a variable with a lowercase (john
instead of John
and str
instead of Str
), and to give them names that reflect their type (Str
gives a hint that it's a String
while it is in fact an int
).
EDIT:
Based on your comment, if you would like to call the method workout
the way you're doing, you can move the method to the CharacterAttributes
class, and change it so that it takes a reference to the Character
instance that will be updated.
public static void main(String[] args) {
Character John = new Character("John", 0);
workout(John, 5);
}
public static void workout(Character character, int byAmt) {
// use a setter to set the attribute
character.setStr(character.getStr() + byAmt);
}
class Character {
private String name;
private int Str;
public Character(String n, int initialStr) {
name = n;
Str = initialStr;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStr() {
return Str;
}
public void setStr(int str) {
Str = str;
}
}
Upvotes: 5