Java中实现double类型变量值递增并打印的方法求助
搞定你的Elephant类方法实现
嘿,作为Java新手,咱们一步步来完善这个Elephant类,先给你梳理下需要调整和添加的内容:
首先修正构造函数的小问题
你原来的构造函数硬编码了name和weight的值,不管传入的参数,这会导致创建对象时传入的名字和体重完全不起作用,得改成用参数赋值:
public Elephant(String name, double weight) { this.name = name; this.weight = weight; }
添加增加体重的核心方法
咱们创建一个eatFood方法,接收食物重量作为参数,更新体重后按你要求的格式打印语句:
// 让大象进食并更新体重的方法 public void eatFood(double foodAmount) { this.weight += foodAmount; // 把食物重量加到当前体重上 // 用printf格式化输出,保证小数格式和示例一致 System.out.printf("The elephant has eaten %.1f kilograms of food and now weighs %.1f%n", foodAmount, this.weight); }
这里用printf来控制输出格式,%.1f可以确保输出一位小数,和你给出的7.5的格式匹配。
补充标准的getter方法
你提到了getter,咱们加上规范的getter方法,方便后续获取对象的属性值:
// 获取大象名字的getter public String getName() { return name; } // 获取大象体重的getter public double getWeight() { return weight; }
完整的可运行代码
最后在main方法里创建Elephant对象,调用eatFood方法测试效果:
public class Elephant { public static void main(String[] args) { // 创建一个大象实例,比如名字叫Elly,初始体重100公斤 Elephant elly = new Elephant("Elly", 100.0); // 调用进食方法,传入7.5公斤食物 elly.eatFood(7.5); }// end of main // instance variables private String name ; private double weight ; // constructor public Elephant(String name, double weight) { this.name = name; this.weight = weight; }// end constructor // getter方法 public String getName() { return name; } public double getWeight() { return weight; } // 进食增加体重的方法 public void eatFood(double foodAmount) { this.weight += foodAmount; System.out.printf("The elephant has eaten %.1f kilograms of food and now weighs %.1f%n", foodAmount, this.weight); } }
运行这段代码,你就会看到输出:The elephant has eaten 7.5 kilograms of food and now weighs 107.5,完全符合你的要求~
内容的提问来源于stack exchange,提问作者Brian Morrison
相关产品推荐
相关产品推荐

