英文:
How to find highest odd number in an array and return 0 if no odd number is present in Java?
问题
如何在数组中找到最大的奇数并将其打印到标准输出?如果数组中没有奇数,则应返回 0。
我已经编写了程序,但不知道如何在数组中未找到奇数的情况下返回 0。
public class Highestodd_number {
public int odd() {
int[] arr = { 4, 6, 9};
int max = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 != 0 && arr[i] > max) {
max = arr[i];
System.out.println(max);
}
}
return 0;
}
public static void main(String[] args) {
Highestodd_number rt = new Highestodd_number();
rt.odd();
}
}
英文:
How to find highest odd number in the array and print that to the standard output? It should return 0 if the array has no odd numbers.
I have written the program, but not getting how to return 0 in case no odd number was found in the array.
public class Highestodd_number {
public int odd() {
int[] arr = { 4, 6, 9};
int max = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 != 0 && arr[i] > max) {
max = arr[i];
System.out.println(max);
}
}
return 0;
}
public static void main(String[] args) {
Highestodd_number rt = new Highestodd_number();
rt.odd();
}
}
答案1
得分: 1
以下是翻译好的内容:
使用Java 8流可以实现此任务,代码更简洁:
public static int findMaxOddOr0(int[] arr) {
return Arrays.stream(arr)
.filter(x -> x % 2 != 0)
.max()
.orElse(0);
}
public static void main(String args[]) {
int[][] tests = {
{4, 6, 9},
{2, -2, 8, 10},
{-5, -7, -3, 12}
};
Arrays.stream(tests)
.forEach(arr ->
System.out.printf("%s -> %d%n", Arrays.toString(arr), findMaxOddOr0(arr)));
}
输出:
[4, 6, 9] -> 9
[2, -2, 8, 10] -> 0
[-5, -7, -3, 12] -> -3
英文:
It is possible to implement this task using Java 8 streams with less boilerplate code:
public static int findMaxOddOr0(int[] arr) {
return Arrays.stream(arr) // convert array to IntStream
.filter(x -> x % 2 != 0) // filter all odd values
.max() // find optional max
.orElse(0); // or 0 if no max odd is found
}
public static void main(String args[]) {
int[][] tests = {
{4, 6, 9},
{2, -2, 8, 10},
{-5, -7, -3, 12}
};
Arrays.stream(tests)
.forEach(arr ->
System.out.printf("%s -> %d%n", Arrays.toString(arr), findMaxOddOr0(arr)));
}
Output:
[4, 6, 9] -> 9
[2, -2, 8, 10] -> 0
[-5, -7, -3, 12] -> -3
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论