簡體   English   中英

Java無法在單獨的文件上找到特定的方法

[英]Java cannot find a specific method on a seperate file

我使用的是Visual Studio Code,我只是在其中創建了一個帶有“項目”的文件夾,我不喜歡將netbeans,eclipse等用於小型程序。

因此,我正在創建一個小程序,我懷疑它是否會起作用,但它確實適用於mos部分,它創建了一個像角色扮演角色一樣的rpg和第二個角色,並創建了一個模擬戰斗,其中一個角色基於一個屬性獲勝。 一切似乎都正常,但是當我調用方法Battle(oumar, aisha); ,它需要兩個字符並使它們戰斗,它會顯示一條錯誤消息Main.java:6: error: cannot find symbol Battle(oumar, aisha); ^ symbol: method Battle(Character,Character) location: class Main Main.java:6: error: cannot find symbol Battle(oumar, aisha); ^ symbol: method Battle(Character,Character) location: class Main

因此,由於我不是那么有經驗,所以我不確定真正的問題是什么。 這是主類的代碼:

    public class Main {
    public static void main(String args[]) {

        Character oumar = new Character("Oumar", 10);
        Character aisha = new Character("Aisha", 9);
        Battle(oumar, aisha);

    }


}

這是單獨文件中的第二類(仍在同一文件夾中)

public class Character {

    String name;
    int BattlePower;
    int wins;
    Character one;
    Character two;

    public Character(String name, int BattlePower) {
        this.name = name;
        this.wins = wins;
        System.out.println("New character: "+ name);
        this.BattlePower = BattlePower;
        this.wins = wins;
        System.out.println(name + "has a Battle Power of " + BattlePower);
    }

    public void Battle(Character one, Character two) {

        this.one = one;
        this.two = two;

        if (one.BattlePower > two.BattlePower ) {
            System.out.print("Character " + one + " has won the Battle!");
            one.wins++;
            System.out.print("Character one now has " + wins + " wins!");
        }
        else if (two.BattlePower > one.BattlePower) {
            System.out.print("Character " + two + " has won the Battle!");
            two.wins++;
            System.out.print("Character two now has " + wins + " wins!");
        }
        else {

            System.out.print("The two characters have tied!");

        }    
    }    
}

任何幫助都將是巨大的,以及將來可能對我有幫助的任何提示。

我相信您將需要使用

oumar.Battle(oumar, aisha)

要么

aisha.Battle(oumar, aisha)

因為該方法位於非靜態類的內部,所以沒有對象引用就無法調用該方法。

如果你想這樣稱呼

Battle(oumar, aisha)

您需要將其移至主類。

另外,在其他IDE上也應該存在此問題。

您可以在Character類中放置一個無參數的構造函數,例如public Character(){}。 然后在Main.java中,可以使用no-arg構造函數創建Character類的對象,然后調用Battle方法,例如Character ch1 = new Character();。 ch1.Battle(烏馬爾,阿伊莎)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM