2013-02-26 45 views
0

我必须创建一个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; 


    } 

} 
+0

我也试着移动循环内调用搜索方法的计数声明,但我仍然得到array2中每个元素的默认值0 – dendoc01 2013-02-26 10:30:28

回答

4

不看你的逻辑的其余部分,这

if(results=false); 

看起来不正确

  1. 是一个错字?您需要if (results == false)或更简洁,if (!results)
  2. 请注意尾随分号,这意味着无论您的if子句的计算结果如何,都会执行以下块。 ;正在创建一个空块,这是有效的。
+0

感谢您的评论我没有注意到,但我仍然得到一个打印当我尝试打印出输入整数之后的array2的任何元素时,即使在修复之后,也是0。 – dendoc01 2013-02-26 09:26:34

0

有两个错误:

  1. break;声明中,如果块不应该在那里:这将打破你圈外的,但你需要的循环来保持迭代阵列上方,直到所有的元素都被复制过了。
  2. 测试是分配错误导致,不比较,所以改为if (!result)

有一些作风问题太:

  1. 你的搜索方法是waaaay到长;您不需要found变量
  2. 为您的参数命名方法如下:在没有arrayarray1的范围内,您有array2。同为count2
  3. 不想iindex为循环变种 - 它只是打字比较少,少到阅读

这更像是它应该是什么样子:

public static boolean search(int[] array, int value, int count) { 
    for(int i = 0; i < count; i++) { 
    if (array[i] == value) { 
     return true; 
    } 
    } 
    return false; 

}

在你的主要方法中,为什么你有一个循环与i和下一个j?让它们都是i - 循环变量只在循环中有作用域,所以没有冲突。

0

除了已经由布莱恩·阿格纽提到if (results=false),我看到:

array[j]=array2[count]; 

你的阵列,在其中未初始化的第二阵列的存储值的输入覆盖值。你可能打算做

array2[count] = array[j]; 

这里。