我正在使用驅動程序類來創建另一個類的對象。當我輸入寵物重量或整數時,數字會變爲0.0。所有的權重變量都聲明爲double,所以我不知道它爲什麼這樣做。爲什麼當我輸入一個整數時,我的Java雙變量類型出現到0.0?
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」,因爲你沒有在它的實例對象上設置一個值。 – msagala25