避免在数组中重复的用户条目

时间:2014-10-27 00:28:20

标签: java arrays duplicates

我正在完成一项任务,如果用户条目已存在于数组中,我需要抛出异常,但我无法使其工作。我必须使用一个数组,它不能是一个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

谢谢!

3 个答案:

答案 0 :(得分:0)

这种逻辑似乎是相反的。

if(!duplicates){

应该是

if(duplicates){

并且,您应该在添加值

之前检查
if (duplicates){
  throw new DuplicateValueException();
}
array[index] = num;
index++;

答案 1 :(得分: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;
    }
}

答案 2 :(得分: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
相关问题