2014-10-27 45 views
0

我正在做一個任務,如果用戶條目已經存在於數組中但我不能讓它工作,我需要拋出異常。我必須使用一個數組,它不能是一個arrayList。如果該條目不存在於數組中,則應該添加它。避免在陣列中重複的用戶條目

這是我到目前爲止有:

try { 
       boolean duplicates = false; 
       num = Integer.parseInt(inputField.getText()); 

       for (int i = 0; i < index; i++){ 
        if (num == (array[i])) { 
         duplicates = true; 
        } 
       } 
       array[index] = num; 
       index++; 
       if(!duplicates){ 
        throw new DuplicateValueException();} 


      } // end try 

謝謝!

+0

是您的排序嗎? – 2014-10-27 00:29:05

+2

如果有**沒有**重複項,那麼您的代碼會拋出一個合適的錯誤,而如果**有**重複項則不會。將'if(!duplicates)'更改爲'if(重複)'。另外,移動'array [index] = num; index ++;'拋出異常之後,或者無論如何你會添加一個元素,例外或者否。 – Amadan 2014-10-27 00:31:44

+0

FWIW - 你可能完全擺脫了'duplicates'變量,只是拋出'DuplicateValueException',你現在把它設置爲'true'。代碼更少,更易於閱讀。 – 2014-10-27 00:45:15

回答

0

這個邏輯似乎被顛倒過來。

if(!duplicates){ 

應該

if(duplicates){ 

而且,你應該檢查你的附加價值

if (duplicates){ 
    throw new DuplicateValueException(); 
} 
array[index] = num; 
index++; 
0

另一種可能的解決方案,更緊湊的前:

try { 
    num = Integer.parseInt(inputField.getText()); 
    int i=0; 
    while((i < index) && (num != array[i])) { 
     i++; 
    }; 
    if (i<index){ //if i<index is because it found an element in the array 
     throw new DuplicateValueException(); 
    } 
    else { //if i=index is because a duplicate element in the array was not found 
     array[index++] = num; 
    } 
} 
0

你可以做如下:

try { 
       boolean duplicates = false; 
       num = Integer.parseInt(inputField.getText()); 

       for (int i = 0; i < index; i++){ 
        if (num == (array[i])) { 
         duplicates = true; 
        } 
       } 
       if(duplicates){ 
        throw new DuplicateValueException();} 
       array[index] = num; 
       index++; 

      } // end try