[英]Error : Cannot resolve method
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. 编译器说“ workout()”方法无法解决。
Thanks! 谢谢!
There's probably a lot of errors, honestly. 老实说,可能有很多错误。
The method belongs to class Character
, so you should call it against the instance John
: 该方法属于Character
类,因此应针对实例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
). 附带说明一下,通常以小写字母开头变量的名称(用john
代替John
,用str
代替Str
),并为它们提供反映其类型的名称( Str
暗示它是String
,实际上是一个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. 根据您的评论,如果您希望以自己的方式调用方法workout
,可以将方法移至CharacterAttributes
类,然后对其进行更改,以使其引用要更新的Character
实例。
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;
}
}
You can't just do workout(5) 你不能只是做运动(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
public int Str
应该是public int str
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.