Java检查数组是否按顺序

时间:2018-04-04 19:27:26

标签: java

我定义了一个包含随机数的数组。我从用户那里得到一些数字并将它们放在其他数组中。我想检查第一个数组是否按顺序包含第二个数组。我的代码不足以检查顺序。它只是检查包含或不包含。 EX:

  

arr1 = [45, 21,1,19 ,8,90,21,2],arr2 = [21,1,19]     结果= TRUE
      arr1 = [45, 21 ,1, 19 ,8,90,21,2],arr2 = [21,19]结果= FALSE

 public class Main  {

 private static int[] array1;

 public static int[] list() {
     array1 = new int[10];
        for(int i=0;i<array1.length;i++)
        {
            array1[i] = randomFill();
        }
        return array1;
    }



 public static void print()
 {
        for(int n: array1)
        {
        System.out.println(n+" ");
        }
 }

 public static int randomFill()
 {

        Random rand = new Random();
        int randomNum = rand.nextInt(90)+10; //to generate two digits number which is between 10-99 to the array
        return randomNum;
 }

 public static void main(String args[])
 {

     list();
     print();

     Scanner s=new Scanner(System.in);

        System.out.println("How many numbers will you add? ");

        int n=s.nextInt();

        int array2[]=new int[n];

        System.out.println("Enter the numbers:");

        for(int i=0;i<n;i++){//for reading array
            array2[i]=s.nextInt();

        }

        for(int i: array2){ //for printing array

            System.out.println(i);

        }
        int result=0;
       for(int i=0;i<array1.length;i++)
       {
           for(int j=0;j<array2.length;j++)
           {

               if(array1[i]==array2[j])
               {
                   result=result+1;

               }

            }

       }
       if(result==n)
       {

           System.out.println("TRUE");
       }
       else
       {
           System.out.println("false");
       }



 }

}

1 个答案:

答案 0 :(得分:1)

这是没有任何助手的艰难方式

    Integer i,j,k;
    Boolean found=false;

    for(i=0;i<arr1.length;i++) {

        // we look for the index of the first element of the second array in the original one
        if(arr2[0] == arr1[i] ) {

            found=true;

            // after that we iterate in both arrays simultaneously
            for(j=1, k=i+1; j<arr2.length; j++,k++) {
                // if we complete the iteration of the original array
                // or if we find any two elements not equal we break 
                // we set then the boolean variable to false
                if( k>=arr1.length || arr2[j] != arr1[k] ) {
                    found=false;
                    break;
                }
            }

            if(found) break;
        }    
    }

    System.out.println(found);