2013-02-26 49 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]; 

這裏。