gpt4 book ai didi

Java检查数组是否按顺序包含某些值

转载 作者:行者123 更新时间:2023-12-02 11:25:34 25 4
gpt4 key购买 nike

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

arr1=[45, 21,1,19 ,8,90,21,2] ,arr2=[21,1,19] result=TRUE
arr1=[45,21,1,19,8,90,21,2] ,arr2=[21,19] result=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");
}



}

}

最佳答案

这是没有任何帮助的艰难方法

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

关于Java检查数组是否按顺序包含某些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49658951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com