我必须创建一个包含 10 个数字的数组,然后将该数组复制到一个没有重复项的新数组中。我已经达到了它会清除重复项的程度,但由于某种原因,在我确定新数组中尚未存在数字后,它不会让我将其放入其中。这是我到目前为止所拥有的。谢谢。
import java.util.*;
import java.io.*;
public class PrintingDistinctNumbers
{
public static void main(String[] args)
{
int[] array=new int[10];
int[] array2=new int[10];
int num1;
int count = 0;
boolean results;
//let the user input 10 numbers
for(int i=0;i<array.length;i++)
{
Scanner input=new Scanner(System.in);
System.out.println("please enter 10 numbers");
num1=input.nextInt();
array[i]=num1;
}
for (int j=0;j<array.length;j++)
{
results=search(array2 ,array[j],count);
if(results=false);
{
array[j]=array2[count];
count++;
break;
}
}
// just a test to make sure the numbers copied over to the new array
System.out.println(array2[0]);
}
//search the second array to see if the int is allready in it
public static boolean search(int[] array2,int value,int count2)
{
//create variables
boolean found;
//set the variables
found= false;
//search the array
for(int index=0;index<count2;index++)
{
if(array2[index]==value)
{
found=true;
break;
}
}
return found;
}
}
最佳答案
在不考虑其余逻辑的情况下,这
if(results=false);
看起来不对
- 这是一个错字吗?您需要
if (results == false)
,或更简洁地说,if (!results)
- 请注意尾部分号,这意味着无论您的
if
子句的计算结果如何,以下 block 都将执行。;
正在创建一个空 block ,它完全有效。
关于java - 简单的数组复制问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15085274/