编写程序,将搜索数组以查找第一个奇数 [英] Write a program that will search an array to find the first odd number

查看:89
本文介绍了编写程序,将搜索数组以查找第一个奇数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法完成此问题。
编写一个程序,该程序将搜索数组以查找第一个奇数。如果找到了奇数
,则在奇数之后找到第一个偶数。返回第一个奇数和第一个偶数之间的距离。如果找不到奇数或奇数之后没有偶数,则返回-1。
我尝试了这个问题,但我无法解决,这是我的代码:

I am not able to complete this question. Write a program that will search an array to find the first odd number. If an odd number is found, then find the first even number following the odd number. Return the distance between the first odd number and the FIRST even number. Return -1 if no odd numbers are found or there are no even numbers following an odd number. I tried this questions but i am not able to solve this is my code:

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;
      } 
    }
  }
}

Runner对于此代码

Runner for this code

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} ) );

  }
}

请帮助我完成此代码我给出了此代码与此跑步者给出的输出。
我需要这个答案。
我需要的正确输出。

Please help me to complete this code and i give the outputs that this code give with this runner. I need this answers. The correct output that i need.

6
2
3
1
-1
4
5
4
-1


推荐答案

我将嵌套一个循环,首先进行迭代以找到第一个奇数;然后从那里进行迭代以获得均匀的值。从第一个奇数开始迭代后,可以终止外循环。像这样的

I would nest a loop, first iterate to find the first odd value; then iterate from there forward for an even value. You can terminate the outer loop once you have iterated from the first odd. Something like

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

这篇关于编写程序,将搜索数组以查找第一个奇数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆