将用户输入存储到变量中

时间:2019-01-29 06:39:36

标签: java

用户输入没有更新相应的变量。 当用户在出现提示时输入数字时,我正在尝试更新Dexterity变量。

我创建了一个setDex方法,该方法应该接收用户输入的数量,并在将其添加到getDex方法时对其进行更新。 getDex方法应检索变量的当前值。

public class SetAttributes {


    double Dexterity;
    double Strength;
    double Intelligence;
    double Stamina;
    double SkillPoints = 50;



    public SetAttributes() {
        this.setDex(0);
        this.setStr(0);
        this.setInt(0);
        this.setSta(0);
        this.setSkillPoints(50);
    }

    public double getSP(){
        return SkillPoints;

    }
    public double getDex() {
        return Dexterity;
    }

    public double getStr(){
        return Strength;
    }

    public double getInt(){
        return Intelligence;
    }

    public double getSta(){
        return Stamina;
    }




    public void setDex(double dexterity) {
        this.Dexterity = Dexterity;
    }
    public void setStr(double strength){
        this.Strength = Strength;
    }
    public void setInt(double intelligence){
        this.Intelligence = Intelligence;
    }
    public void setSta(double stamina){
        this.Stamina = Stamina;
    }
    public void setSkillPoints(double skillPoints) {this.SkillPoints = SkillPoints;};
}




public final class PointSpender {




    public static void Spend(){

        SetAttributes Attribute = new SetAttributes();


        Scanner SkillChoice = new Scanner(System.in);

        System.out.println("What skill do you want to increase? Dex, Str, Sta, or Int?");



        switch(SkillChoice.nextLine().charAt(0)){
            case 'd':
                System.out.println("How many points towards Dexterity?");
                System.out.println("Your current Dexterity is " + Attribute.Dexterity);

          double amount = SkillChoice.nextDouble();



                Attribute.setDex(amount + Attribute.getDex());
              System.out.println(Attribute.Dexterity);

3 个答案:

答案 0 :(得分:1)

您所有的setter方法都遇到相同的问题(这就是为什么您应该遵循诸如camelCase之类的约定)的原因,所以让我们选择其中的任何一个。

public void setSta(double stamina){
    this.Stamina = Stamina;
}

如您所见,您将类级别变量Stamina设置为等于变量Stamina。方法参数称为stamina。因此,您将this.Stamina设置为本身。

答案 1 :(得分:0)

在Java变量中,区分大小写

this.Dexterity = Dexterity;

应该是

this.Dexterity = dexterity;

否则,他们指的是同一个变量

答案 2 :(得分:0)

public void setDex(double dexterity) {
    this.Dexterity = Dexterity;
}

首先,this.Dexterity = Dexterity;必须为this.Dexterity = dexterity;,因为dexterity是需要分配给Dexterity的变量。 而且,当您使用this.Dexterity = Dexterity;时,实际上是在将Dexterity的值分配给Dexterity,这实际上是没有意义的。

您编写的所有setter方法都存在相同的问题。

最后尝试维护命名约定。