gpt4 book ai didi

java - 通过创建方法来比较两个对象

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

按照Oracle学院Java基础知识,我走进了一堵墙(我不明白它在学院中是如何解释的)

尝试/解决它:

  1. Create a method nicestFish that takes in two fish as parameters, compares the friendliness level of two fish, and returns the fish with the higher friendliness. Test this method with the fish defined in problem 6.

主要:

public class index {
public static void main(String[] args) {
Fish Amber = new Fish("AngelFish", 5);
Fish James = new Fish("Guppy", 3);
}
}

类(class):

public class Fish {
String typeOfFish;
int friendliness;

public Fish(){
typeOfFish = "unknown";
friendliness = 3;
}

public Fish(String t, int f) {
this.typeOfFish = t;
this.friendliness = f;
}

public int getFriendliness(){
return friendliness;
}
}

最佳答案

我猜他们希望你做一个静态比较方法,因为他们指定它需要两条鱼作为参数

public class Fish
{
...
public static Fish nicestFish(Fish f1, Fish f2)
{
//find out which fish is nicest, and return it
}
...
}

要调用静态方法,不需要对象引用:

Fish fish1 = ...
Fish fish2 = ...
Fish nicest = Fish.nicestFish(fish1, fish2);

关于java - 通过创建方法来比较两个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33023447/

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