2014-10-27 67 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