首页 > 解决方案 > 编写一个程序,返回数组中大于 11 的前 3 个数字,然后返回你找到的数?

问题描述

编写一个程序,返回大于 11 的前 3 个数字。如果小于 3 个大于 11 的数字,则返回找到的数量。您将始终返回一个大小为 3 的数组。如果没有 3 个大于 11 的数字,则零将填充数组。我如何解决这个问题。这就是我开始我的代码的方式:

public class RayGetNums
{
    //method go will return an array
    //containing the first 3 numbers
    //greater than 11
    public static int[] go(int[] ray)
    {
        return null;
    }
}

我在这个问题上使用的 Runner 是这样的:

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

        System.out.println( rt.go( new int[]{-99,1,2,3,4,5,6,7,8,9,10,12345} ) );
        System.out.println( rt.go( new int[]{10,9,8,7,6,5,4,3,2,1,-99} ) );
        System.out.println( rt.go( new int[]{10,20,30,40,50,-11818,40,30,20,10} ) );
        System.out.println( rt.go( new int[]{32767} ) );
        System.out.println( rt.go( new int[]{255,255} ) );
        System.out.println( rt.go( new int[]{9,10,-88,100,-555,1000} ) );
        System.out.println( rt.go( new int[]{10,10,10,11,456} ) );
        System.out.println( rt.go( new int[]{-111,1,2,3,9,11,20,30} ) );
        System.out.println( rt.go( new int[]{9,8,7,6,5,4,3,2,0,-2,-989} ) );
        System.out.println( rt.go( new int[]{12,15,18,21,23,1000} ) );
        System.out.println( rt.go( new int[]{250,19,17,15,13,11,10,9,6,3,2,1,-455} ) ); 
        System.out.println( rt.go( new int[]{9,10,-8,10000,-5000,1000} ) );
  }
}

我需要我们这个跑步者的答案:

[12345, 0, 0]
[0, 0, 0]
[20, 30, 40]
[32767, 0, 0]
[255, 255, 0]
[100, 1000, 0]
[456, 0, 0]
[20, 30, 0]
[0, 0, 0]
[12, 15, 18]
[250, 19, 17]
[10000, 1000, 0]

谢谢

标签: javaarrays

解决方案


使用循环将大于 11 的元素添加到数组并返回。

public static int[] go(int[] ray)
{
    int[] res = new int[]{0,0,0};
    int count = 0;
    for (int i = 0; i < ray.length && count < 3; i++) {
        if ( ray[i] > 11 ) {
            res[count++] = ray[i];
        }
    }
    return res;
}

推荐阅读