gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:02:02 25 4
gpt4 key购买 nike

我正在使用驱动程序类来创建另一个类的对象。当我输入宠物体重或整数时,数字为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com