【发布时间】:2017-02-16 04:59:48
【问题描述】:
我正在使用驱动程序类来创建另一个类的对象。当我输入宠物重量或整数时,数字为 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.");
}
}
这是我的宠物班
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;
}
}
【问题讨论】:
-
为什么要为每个属性使用一个新的
Pet实例?他们都是同一个宠物,不是吗?您正在为您的petName实例设置权重值,并将其从您的petWeight实例中写出。只需创建一个Pet并使用它来设置/获取所有属性。 -
请发布您的 setWeight(double w) 方法。
-
实例太多,而不是只有 1 个。并且
petWeight.getWeight()将具有默认值0.0,因为您没有在其实例对象上设置值。