[英]'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.