gpt4 book ai didi

java - Java中查找最大值的所有者

转载 作者:行者123 更新时间:2023-12-01 19:34:40 24 4
gpt4 key购买 nike

尝试一些java代码,我想找到最喜欢的东西的狗。本质上,是对每只狗的 favThings 值进行比较。我尝试了以下方法,但没有成功。此外,如果您能分享一些关于以下内容的建议,那就太棒了,因为我是 Java 新手。

public class Dog {
String breed;
boolean hasOwner;
int age;
int favThings;
public Dog(String dogBreed, boolean dogOwned, int dogYears, int things) {
breed = dogBreed;
hasOwner = dogOwned;
age = dogYears;
favThings = things;
}
public static void main(String[] args) {
Dog fido = new Dog("poodle", false, 4, 31);
Dog nunzio = new Dog("shiba inu", true, 12, 3);
Dog las = new Dog("Collie", true, 5, 4);
System.out.println("The dog with the most fav things is " + max(Dog.favThings));
}
}

问题出在最后一行。为了获得最喜欢的东西的狗的名字,我写了: max(Dog.favThings) 这不是所需要的。

它返回的是:

Dog.java:35: error: cannot find symbol
System.out.println("The dog with the most fav things is "+ max(Dog.favThings));
^
symbol: method max(int)
location: class Dog
2 errors

最佳答案

您可能必须将所有 Dog 实例放入列表中,然后使用允许指定自定义比较器的流 max(..) 方法:

public static void main(String[] args) {
Dog fido = new Dog("poodle", false, 4, 31);
Dog nunzio = new Dog("shiba inu", true, 12, 3);
Dog las = new Dog("Collie", true, 5, 4);

List<Dog> list = new ArrayList<>();
list.add(fido);
list.add(nunzio);
list.add(las);

// We use a custom comparator that compares two Dog instances 'a' and 'b' based on the favThings field:
Dog maxDog = Collections.max(list, (a,b) -> Integer.compare(a.favThings, b.favThings));

System.out.println("The dog with the most fav things is " + maxDog.breed);
}

关于java - Java中查找最大值的所有者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58269621/

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