java 如何编写一个接受 int 变量并返回最大的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13465320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write a method that takes int variables and returns the largest?
提问by user1837411
I am trying to write a method that compares 3 numbers and returns the largest of them.
我正在尝试编写一个方法来比较 3 个数字并返回其中最大的一个。
This is my code, but it doesn't work...
这是我的代码,但它不起作用...
public int max(int x, int y, int z){
return Math.max(x,y,z);
}
How can my code be corrected?
如何更正我的代码?
回答by wattostudios
Try this...
试试这个...
public int max(int x, int y, int z){
return Math.max(x,Math.max(y,z));
}
The method Math.max()
only accepts 2 arguments, so you need to perform this method twice if you want to compare 3 numbers, as per the code above.
该方法Math.max()
只接受 2 个参数,因此如果要比较 3 个数字,则需要执行此方法两次,如上面的代码所示。
回答by Ted Hopp
For any number of int values, you can do this (tip 'o the hat to zapl):
对于任意数量的 int 值,您可以这样做(提示 zapl 的帽子):
public int max(int firstValue, int... otherValues) {
for (int value : otherValues) {
if (firstValue < value ) {
firstValue = value;
}
}
return firstValue;
}
回答by Reimeus
回答by Maciej Ziarko
If Apache Commons Lang is on your classpath, you can use NumberUtils
.
如果 Apache Commons Lang 在您的类路径中,您可以使用NumberUtils
.
There are several max
, min
functions. Also one you wanted.
有几个max
,min
功能。也是你想要的。
Check API: http://commons.apache.org/lang/api/org/apache/commons/lang3/math/NumberUtils.html
检查 API:http: //commons.apache.org/lang/api/org/apache/commons/lang3/math/NumberUtils.html
Commons Lang is useful as it extends standard Java API.
Commons Lang 很有用,因为它扩展了标准 Java API。
回答by Bohemian
Try using the JDK api:
尝试使用 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);
}