如何更正教程中的java代码?

goqiplq2  于 2021-06-25  发布在  Java
关注(0)|答案(2)|浏览(349)

关闭。这个问题需要更加突出重点。它目前不接受答案。
**想改进这个问题吗?**通过编辑这篇文章更新这个问题,使它只关注一个问题。

8天前关门了。
改进这个问题
我从一个learnjava应用程序(codemurai)将这段代码复制到eclipse中,但出现了错误。由于我对java不太熟悉,所以我不确定如何构造,所以我尝试了两种不同的方法。作为given:-

String name;
int weaponDamage;
int health;
double score;

Player codemurai = new Player();
codemurai.name = "Codemurai";
codemurai.weaponDamage = 100;
codemurai.health = 100;
codemurai.score = 1500;

我试过了way:-

public class Player {

public static void main(String[] args) {
    String name;
    int weaponDamage;
    int health;
    double score;

    Player codemurai = new Player();
    codemurai.name = "Codemurai";
    codemurai.weaponDamage = 100;
    codemurai.health = 100;
    codemurai.score = 1500;
}
}

并在最后一行获取“name cannot be resolved”。
然后我试着this:-

public class Player {
    String name;
    int weaponDamage;
    int health;
    double score;

    Player codemurai = new Player();
    codemurai.name = "Codemurai";
    codemurai.weaponDamage = 100;
    codemurai.health = 100;
    codemurai.score = 1500;

    public static void main(String[] args) {    
    }
}

并获取“variabledeclaratorid expected”。
我知道这段代码不会有任何输出,但是我如何使它无错误运行,这些错误到底意味着什么?

bwitn5fc

bwitn5fc1#

@abra解决方案的另一个替代方案是创建一个只包含属性的player类,而question的类示例化一个player。

package com.stackoverflow.question;

class Player {
    String name;
    int weaponDamage;
    int health;
    double score;
}

public class Question {
    public static void main(String[] args) {
        Player codemurai = new Player();
        codemurai.name = "Codemurai";
        codemurai.weaponDamage = 100;
        codemurai.health = 100;
        codemurai.score = 1500;
    }
}
yhuiod9q

yhuiod9q2#

public class Player {
    String name;
    int weaponDamage;
    int health;
    double score;

    public static void main(String[] args) {
        Player codemurai = new Player();
        codemurai.name = "Codemurai";
        codemurai.weaponDamage = 100;
        codemurai.health = 100;
        codemurai.score = 1500;
    }
}

在方法中声明变量时,它们是该方法的局部变量。似乎你想要这些变量 name , weaponDamage , health 以及 score 成为班级的一员 Player . 因此,您必须在 main 方法。

相关问题