开发者

How to prevent a user from duplicating an entry (Java)

I am writing a simple program where the user enters a name and an integer. If the integer was not already used, the name goes into an array. My problem is that I can't seem to figure out how to check the integer when it is entered to see if it was already used (duplicated). I tried putting the integers into an array, but could not get it to work. Please keep in mind that I am a complete novice. So in the code below, after the user enters a name, he/she enters a time (integer) and if the time was not already used, it is valid; if it was used, I'll need to throw an exception. So far, all I have is the code working for the name (adding it to the array).

public void enterName()
{

    Scanner keyboard = new Scanner(System.in);

    for(i = 0; i < arrayNames.length; i++)
    {    开发者_运维百科       
        System.out.println("Please enter your name.");
        names = keyboard.nextLine();

            arrayNames[i] = names;              
            System.out.println("name is in");           
    }
    System.out.println("array is full");


}


Wouldn't it be easier to just use another data structure (e.g. a Set, since it contains no duplicate items)? If you attempt to add an item that's already in the set, it will return false.


Here is a hint: add your integers to a Set<Integer>, and use contains() to check whether the just-entered number is a duplicate.

As an alternative to contains(), you could check the return value of add() and throw an exception if it returns false.


If you absolutely must use an array, here's how to check for duplicate entries:

public boolean contains(int[] numbers, int searchedNumber) {
    for (int number : numbers) {
        if (number == searchedNumber) {
            return true;
        }
    }

    return false;
}    

EDIT

The expression for (int number : numbers) basically means for each int of the int array do. Internally, an Iterator is created, which is then used to iterate over the elements of the array (or collection).

But for the moment, you can think of it being (semantically) the same as:

for (int i = 0; i < numbers.length; i++) {
    if (numbers[i] == searchedNumber) {
        return true;
    }
}


No matter what data structure you use, for every entry you make, you have to search (or let the structure do the searching) to see if the entry is existent or not. In case it is not you add and increment your subscript. Check the logic of your algorithm again!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜