如何在数组中找到最大的奇数,并在没有奇数的情况下返回0(Java)?

huangapple go评论79阅读模式
英文:

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 &lt; arr.length; i++) {
			if (arr[i] % 2 != 0 &amp;&amp; arr[i] &gt; 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 -&gt; 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 -&gt; 
              System.out.printf(&quot;%s -&gt; %d%n&quot;, Arrays.toString(arr), findMaxOddOr0(arr)));
}

Output:

[4, 6, 9] -&gt; 9
[2, -2, 8, 10] -&gt; 0
[-5, -7, -3, 12] -&gt; -3

huangapple
  • 本文由 发表于 2020年9月7日 17:32:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63774904.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定