'Cannot find symbol' 从类创建新对象时出错?


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 类创建新对象时,出现此错误:

Frank.java:5: error: cannot find symbol
Monster NewMonster = new Monster();
^

符号:类怪物 地点:弗兰克类

我是Java的新手,所以很抱歉,如果这是一个简单/容易的修复,但我研究的所有内容都没有为我提供此错误的解决方案。

提前感谢您的任何回复/反馈。

1 你只需要定义一个公共类

,它将按照你的java文件名(.java(保存2 个对象引用将始终为小写

类怪物 {

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 文件中的公共类,或者创建两个不同的 Java 类并导入。 公开课 弗兰克 {

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());

} }

输出:弗兰克的攻击值为 20

在 Java 中,不允许在一个文件中有多个公共类。因此,您需要删除其中一个类的公共修饰符,或者将 main 方法放在公共类中。我做了后者,因为没有必要将 main 方法放在单独的类中只是为了实例化你的对象。

我已经更新了您的代码,它现在可以运行

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(){}
}

最新更新