gpt4 book ai didi

java - 从java中的类添加值

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:16:06 25 4
gpt4 key购买 nike

我的书中有一个问题是这样说的(没有答案):

Suppose we have a class Beta declared with the header:

class Beta extends Alpha

so Beta is a subclass of Alpha, and in class Alpha there is a method with header:

public int value(Gamma gam) throws ValueException

Write a static method called addValues which takes an object which could be of type ArrayList<Alpha> or ArrayList<Beta>, and also an object of type Gamma. A call to the method addValues must return the sum obtained by adding the result of a call of value on each of the objects in the ArrayList argument, with the Gamma argument as the argument to each call of value. Any call of value which causes an exception of type ValueException to be thrown should be ignored in calculating the sum.

我的尝试:

public static int addValues(ArrayList<? extends Alpha> arr, Gamma gam) {
int sum = 0;
for (int i = 0; i < arr.size(); i++) {
try {
sum += arr.get(i) + gam;
} catch (Exception e) {
i++;
}
}
return sum;
}

虽然我知道对于初学者来说,行 sum += arr.get(i) + gam会给我一个错误,因为它们不是直截了当的int可以添加的。这本书没有提供关于这个问题的更多信息,所以我在这里写的是这个问题所需的一切。

最佳答案

您应该调用 value 方法以获得您应该添加的值。

除此之外,您还可以使用增强的 for 循环来使您的代码更简洁。

public static int addValues(ArrayList<? extends Alpha> arr, Gamma gam) 
{
int sum = 0;
for (Alpha alpha : arr) {
try {
sum += alpha.value(gam);
} catch (ValueException e) {
}
}
return sum;
}

关于java - 从java中的类添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29742730/

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