【问题标题】:Write a program that will search an array to find the first odd number编写一个程序,搜索一个数组以找到第一个奇数
【发布时间】:2020-01-11 22:39:02
【问题描述】:

我无法完成这个问题。 编写一个程序,搜索一个数组以找到第一个奇数。如果一个奇怪的 找到数字,然后找到奇数之后的第一个偶数。返回第一个奇数和第一个偶数之间的距离。如果没有找到奇数或奇数后面没有偶数,则返回 -1。 我试过这个问题,但我无法解决这是我的代码:

public class RayOddtoEven
{
  public static int go(int[] ray)
  {
    int result = 0;
    boolean oddExists = false;
    int oddIndex = 0;
    for (int i = 0; i < array.length; i++)
    {
      if (array[i] % 2 != 0)
      {
        oddExists = true;
        oddIndex = array[i];
        break;
      } 
    }
  }
}

此代码的跑步者

class Main 
{
  public static void main(String[] args) 
  {
    RayOddtoEven rt = new RayOddtoEven();

    System.out.println( rt.go( new int[]{7,1,5,3,11,5,6,7,8,9,10,12345,11} ) );
    System.out.println( rt.go( new int[]{11,9,8,7,6,5,4,3,2,1,-99,7} ) );
    System.out.println( rt.go( new int[]{10,20,30,40,5,41,31,20,11,7} ) );
    System.out.println( rt.go( new int[]{32767,70,4,5,6,7} ) );
    System.out.println( rt.go( new int[]{2,7,11,21,5,7} ) );
    System.out.println( rt.go( new int[]{7,255,11,255,100,3,2} ) );
    System.out.println( rt.go( new int[]{9,11,11,11,7,1000,3} ) );
    System.out.println( rt.go( new int[]{7,7,7,11,2,7,7,11,11,2} ) );
    System.out.println( rt.go( new int[]{2,4,6,8,8} ) );

  }
}

请帮我完成这段代码,我给出这段代码与这个跑步者一起给出的输出。 我需要这个答案。 我需要的正确输出。

6
2
3
1
-1
4
5
4
-1

【问题讨论】:

  • 你的方法没有返回任何东西。
  • 是的,我知道,但我不明白。所以这就是我不回来的原因

标签: java arrays


【解决方案1】:

我会嵌套一个循环,首先迭代找到第一个奇数值;然后从那里向前迭代以获得偶数。从第一个奇数开始迭代后,您可以终止外循环。类似的东西

public static int go(int[] ray) {
    for (int i = 0; i < ray.length; i++) {
        if (ray[i] % 2 != 0) {
            for (int j = i + 1; j < ray.length; j++) {
                if (ray[j] % 2 == 0) {
                    return j - i;
                }
            }
            break;
        }
    }
    return -1;
}

输出(按要求)

6
2
3
1
-1
4
5
4
-1

【讨论】:

    猜你喜欢
    • 2013-02-14
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 2021-04-01
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    相关资源
    最近更新 更多