gpt4 book ai didi

java - 创建带有形式参数的方法来设置值和返回字符串的方法

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

我目前正在开展一个实验室,该实验室要求我向教科书中找到的代码添加额外的代码。我尝试在这里寻找解决我的问题的方法,但找不到。

我们对实验室的说明如下:

Add another instance variable to the Dog class called weight which is an int variable.

Add another method to the Dog class called setWeight() which has an int formal parameter which sets the weight of the dog.

Add another method to the Dog class called getSize() that returns a String. It will use the weight of the dog as follows:

If the dog is less than 30 pounds, it returns the String small. If the dog is between 30 and 60 pounds, it returns the String medium. If the dog is over 60 pounds, it returns the String large.

Add the following code to the DogDemo class:

Dog otto = new Dog();
otto.name = "Otto";
otto.age = 7;
otto.breed = "German Shepherd";
otto.setWeight(50);
System.out.println();
otto.writeOutput();
System.out.println("Otto is a " + otto.getSize() + " dog.");

到目前为止,我还无法弄清楚如何正确设置 setWeight() 方法和 getSize() 方法,而且我也不确定我是否正确定义了实例变量权重。这是到目前为止我的代码。

package dogdemo;

public class Dog
{
public String name;
public String breed;
public int age;
public int weight;
public int getSize()
{
if (weight < 30) {
getSize = ("small");
} else {
if (weight >= 30 && weight <=60)
getSize=("medium");
} else {
getSize=("large");
}
}
public void writeOutput()
{
System.out.println("Name: " + name);
System.out.println("Breed: " + breed);
System.out.println("Age in calendar years: " +
age);
System.out.println("Age in human years: " +
getAgeInHumanYears());
System.out.println();
}
public int getAgeInHumanYears()
{
int humanAge = 0;
if (age <= 2)
{
humanAge = age * 11;
}
else
{
humanAge = 22 + ((age-2) * 5);
}
return humanAge;
}
}

这是实际输出信息的另一个类代码。

package dogdemo;

public class DogDemo
{
public static void main(String[] args)
{
Dog balto = new Dog();
balto.name = "Balto";
balto.age = 8;
balto.breed = "Siberian Husky";
balto.writeOutput();
Dog scooby = new Dog();
scooby.name = "Scooby";
scooby.age = 42;
scooby.breed = "Great Dane";
System.out.println(scooby.name + " is a " +
scooby.breed + ".");
System.out.print("He is " + scooby.age +
" years old, or ");
int humanYears = scooby.getAgeInHumanYears();
System.out.println(humanYears + " in human years.");
}
}

正如您所看到的,在公共(public)类 Dog 中,我尝试创建 getSize() 方法,但并不真正知道我在做什么。我什至没有尝试创建 setWeight() 方法,因为我完全不确定如何编写该方法。为了创建实例变量权重,我将其公开,但我认为它可能必须是私有(private)的。

提前致谢,感谢所有帮助。

最佳答案

我不明白您的 setWeight() 问题是什么。

这很简单:

public void setWeight(int weight)
{
this.weight = weight;
}

至于getSize(),逻辑基本正确,但必须返回一个字符串。

public String getSize()
{
if (weight < 30) {
return "small";
} else {
if (weight >= 30 && weight <=60) {
return "medium";
} else {
return "large";
}
}
}

关于java - 创建带有形式参数的方法来设置值和返回字符串的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26113035/

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