簡體   English   中英

非常簡單的Java語法錯誤

[英]Very simple Java syntax errors

因此,我試圖創建一個非常簡單的程序來練習一些基本的Java格式化技巧。 但是,有關“ fight()”的某些事情使我的編譯器發瘋。 有人知道為什么嗎? 預先感謝您收到的任何答復,代碼如下:

class Hero{
    String name;
    int Intelligence;
    boolean parents;

    public static fight(Hero1, Hero2){
    if(Hero1.Intelligence>Hero2.Intelligence){
        return(Hero1.name+" is the winner");
    else
        return(Hero2.name+" is the winner");
        }
    }
}



class HeroMain{
    public static void main(String[] args){
    Hero Superman = new Hero();
    Superman.name = "Superman";
    Superman.Intelligence = 7;
    Superman.parents = false;

    Hero Batman = new Hero();
    Batman.name = "Batman";
    Batman.Intelligence = 8;
    Batman.parents = false;

    public fight(Superman, Batman);
    }
}

你需要寫

public static String fight(Hero hero1, Hero hero2) {

您還需要按如下方式調用fight()

Hero.fight(Superman, Batman);

同樣,作為Java的經驗法則,您應該以小寫字母開頭所有變量。 那只是編碼約定。

就像La-comadreja所說的那樣,問題在於您試圖返回一個字符串,但您並未在方法標題中定義它。

public static void fight() {}不返回,它只是執行某些操作public static String fight(){}返回一個String

以下是一些更正:

class Hero{
    String name;
    int Intelligence;
    boolean parents;

    public static String fight(Hero Hero1, Hero Hero2){ <-- specify type of parameter and return type
        if(Hero1.Intelligence>Hero2.Intelligence) <-- you had a curly-brace problem
            return(Hero1.name+" is the winner");
        else
            return(Hero2.name+" is the winner");
    }
}



class HeroMain{
    public static void main(String[] args){
        Hero Superman = new Hero();
        Superman.name = "Superman";
        Superman.Intelligence = 7;
        Superman.parents = false;

        Hero Batman = new Hero();
        Batman.name = "Batman";
        Batman.Intelligence = 8;
        Batman.parents = false;

        String myStr = Hero.fight(Superman, Batman); <-- call a hero's fight method
        System.out.println(myStr); // "Batman is the winner"
    }

}

暫無
暫無

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

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