我正在尝试编写一个比较3个数字并返回其中最大数字的方法。
这是我的代码,但它不起作用......
public int max(int x, int y, int z){
return Math.max(x,y,z);
}
我的代码如何更正?
答案 0 :(得分:5)
试试这个......
public int max(int x, int y, int z){
return Math.max(x,Math.max(y,z));
}
方法Math.max()
只接受2个参数,因此如果要根据上面的代码比较3个数字,则需要执行此方法两次。
答案 1 :(得分:4)
答案 2 :(得分:4)
对于任意数量的int值,你可以这样做(将帽子改为zapl):
public int max(int firstValue, int... otherValues) {
for (int value : otherValues) {
if (firstValue < value ) {
firstValue = value;
}
}
return firstValue;
}
答案 3 :(得分:0)
如果Apache Commons Lang在您的类路径上,您可以使用NumberUtils
。
有几个max
,min
个函数。也是你想要的。
检查API:http://commons.apache.org/lang/api/org/apache/commons/lang3/math/NumberUtils.html
Commons Lang非常有用,因为它扩展了标准Java API。
答案 4 :(得分:0)
尝试使用JDK api:
public static int max(int i, int... ints) {
int nums = new int[ints.length + 1];
nums[0] = i;
System.arrayCopy(ints, 0, nums, 1, ints.length);
Arrays.sort(nums);
return ints[nums.length - 1);
}