[英]'Cannot find symbol' Error when creating a new object from a class?
public class Monster{
public final String TOMBSTONE = "Here Lies a Dead monster";
private int health = 500;
private int attack = 20;
private int movement = 2;
public String name = "Big Monster";
public int getAttack()
{
return attack;
}
public int getMovement()
{
return movement;
}
public int getHealth()
{
return health;
}
public Monster(int health, int attack, int movement)
{
this.health = health;
this.attack = attack;
this.movement = movement;
}
public Monster()
{
}}
public class Frank {
public static void main(String[] args){
Monster NewMonster = new Monster();
NewMonster.name = "Frank";
System.out.println(NewMonster.name + " has an attack value of " + NewMonster.getAttack());
}
}
尝试从我的 Monster class 创建新的 object 时,出现此错误:
Frank.java:5: error: cannot find symbol
Monster NewMonster = new Monster();
^
符号:class 怪物位置:class 弗兰克
我对 Java 很陌生,所以很抱歉,如果这是一个简单/容易的修复,但我研究的所有内容都没有给我解决这个错误的方法。
提前感谢您的任何回复/反馈。
Java 的一个文件中不允许有多个公共类。 因此,您需要删除其中一个类的公共修饰符,或者将主要方法放在公共 class 中。 我做了后者,因为没有必要将主要方法放在单独的 class 中来实例化您的 object。
我已经更新了你的代码,它现在可以运行了
public class Monster{
public static void main(String[] args) {
Monster NewMonster = new Monster();
NewMonster.name = "Frank";
System.out.println(NewMonster.name + " has an attack value of
" + NewMonster.getAttack());
}
public final String TOMBSTONE = "Here Lies a Dead monster";
private int health = 500;
private int attack = 20;
private int movement = 2;
public String name = "Big Monster";
public int getAttack() {
return attack;
}
public int getMovement(){
return movement;
}
public int getHealth(){
return health;
}
public Monster(int health, int attack, int movement){
this.health = health;
this.attack = attack;
this.movement = movement;
}
public Monster(){}
}
1 您必须只定义一个 class 一个公共,它将根据您的 java 文件名(.java)保存
2 object 引用将始终为小写
class 怪物{
public final String TOMBSTONE = "Here Lies a Dead monster";
private int health = 500;
private int attack = 20;
private int movement = 2;
public String name = "Big Monster";
public int getAttack() {
return attack;
}
public int getMovement() {
return movement;
}
public int getHealth() {
return health;
}
public Monster(int health, int attack, int movement) {
this.health = health;
this.attack = attack;
this.movement = movement;
}
public Monster() {
}
} // 只有 Frank 可以是单个 java 文件中的公共 class,否则创建两个不同的 java 类并导入。 公共 class 弗兰克 {
公共 static 无效主(字符串 [] 参数){
Monster newMonster = new Monster();
newMonster.name = "Frank";
System.out.println(newMonster.name + " has an attack value of " + newMonster.getAttack());
} }
Output:弗兰克的攻击值为20
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.