java - 当我输入一个整数时,为什么我的 Java 双变量类型会变成 0.0?

标签 java accessor

我正在使用驱动程序类来创建另一个类的对象。当我输入宠物体重或整数时,数字为 0.0。所有权重变量都声明为 double ,所以我不知道为什么要这样做。

  import java.util.Scanner;

    public class PetAssignment {

        public static void main(String[] args) 
        {
            String nameAndType;
            int yrs;
            double lbs;

            //Scanner object for the keyboard input
            Scanner answers = new Scanner(System.in);

            //Pet objects used for calling accessor methods
            Pet petName = new Pet();
            Pet petType = new Pet();
            Pet petAge = new Pet();
            Pet petWeight = new Pet();

            //A bunch of other code and pet attributes

            //Input for the weight of pet
            System.out.print("How many pounds does your pet weight? ");
            lbs = answers.nextDouble();
            petName.setWeight(lbs);

            //Print out of the user's answers
            System.out.println(""); 
            System.out.println("You have a "+ petType.getType() + ". That is named " 
                + petName.getName()+ " and is " 
                + petAge.getAge() + " years old and weighs " 
                + petWeight.getWeight() + " lbs.");         
        }
    }

这是我的宠物类(class)

 public class Pet 
    {
      private String name;
      private String type;
      private int age;
      private double weight;    
      /*
       * a bunch of other code
       */
      public void setWeight(double petWeight)
      {
          weight = petWeight;
      }
      /*
       * a bunch of other code
       */
      public double getWeight()
      {
          return weight;
      }
    }

最佳答案

错误的是您使用此代码来设置值

 petName.setWeight(lbs);

并用它来检索值

 Pet petWeight = new Pet();

它们是2个不同的对象,您必须在设置、检索中为2个语句使用相同的对象 通过放置

petWeight.setWeight(lbs);

而不是

petName.setWeight(lbs);

解决了

关于java - 当我输入一个整数时,为什么我的 Java 双变量类型会变成 0.0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42265324/

相关文章:

Java-Thread.setPriority()错误: cannot find symbol (the period between Thread and setPriority)

Java调用函数两次时出现越界异常?

c# - 在 C# 中是否有可能知道谁调用了静态属性/访问器?

java - 在类内部使用访问器方法?

没有私有(private)变量的 C# 自定义 getter/setter

java - 在 Eclipse 中停止 vertx verticle

java - SIP 调用 Invite 请求方法后如何发送 RTP 数据包?

java - 堆排序 StackOverflow 错误

objective-c - 键值编码是否支持声明的属性的自定义访问器名称?

c# - 使用多维数组索引器的最有效方法