0

I am working on this project that wants me to write a program that inputs 20 numbers, each of which is between 10 and 100, inclusive. As each number is read, display it only if it is not a duplicate of a number already read. The only part I am confused about is how to go about checking for duplicate values that the user may enter. And IF the user does input a duplicate value, it should not be stored again.

In addition, the value entered should be printed out after it is entered along side the value that have been previously entered by the user such as: 23 23 45 23 45 67 23 45 67 12 and so on.

I am still fairly new at java programming so any help would be great.

import java.util.*;

public class NumberArray 
{
    public static void main(String[] args) 
    {
        // declare an array with 20 elements

        Scanner input = new Scanner( System.in );

            int num[] = new int[20];
            int index = 0;
            int enteredNumbers = 0;

            while( enteredNumbers < num.length )
            {
                System.out.print( "\nEnter number: ");
                int numberInput = input.nextInt();

                if (numberInput >= 10 && numberInput <= 100)
                {
                    num[index] = numberInput;
                    System.out.println("Number stored.");
                }

                //Check if numbers repeat--if not add to array
                else if(num[index] == numberInput)
                {
                    System.out.println("Duplicate value entered!\n");
                }

                else
                {
                    System.out.println("Invalid Number, enter within range.\n");
                }

                // increment number of entered numbers
                System.out.print(num[index] + "  ");
                System.out.println();
                enteredNumbers++;
                index++;
            }
      }
}
2
  • The "else if( num[index] == numberInput )" will run only if the number is not between 10 and 100. I don't think this is what you want. Commented Jul 9, 2014 at 2:13
  • 1
    Furthermore, when using an array, you'll need to loop over all the previous numbers you've entered to search for a duplicate. A set would do what you're after better. Commented Jul 9, 2014 at 2:15

3 Answers 3

2

If you are looking for duplicates from input numbers, one suggestion would be to have a boolean array indexed from 1 to 100 all set to false. Once you read a number from the user, use that inputted number as the index for the array and mark that position true if that position was previously false. If you find out that the position was true previously, then you found a duplicate and you could do your printing.

Sign up to request clarification or add additional context in comments.

5 Comments

Best approach if memory is plentiful and CPU is critical. However I'd keep it simple and search the array instead. I wonder if a new coder would find searching the array, or this approach easier?
@WilliamMorrison: how difficult is if (used[i]) getAnotherNum();?
When I was writing the solution, I tried to illustrate a new way of thinking about this problem for a new coder so he could possibly use this in the future if necessary.
This is exactly what I would do. The set is small in this case but if expanded to a couple thousand possibilities iterating would be costly.
@ChiefTwoPencils its difficult for a newer coder to deal with referencing 2 arrays by index. Arrays are cake for an experienced coder, its hard to imagine what newbs find difficult.
1

We'll stick with just arrays since you're a newer programmer, and are likely not familiar with the myriad of collections available to you.

First, you need a method to check the entire array of entered values for duplicates.

//if the array contains the number just input, return true.
//else return false.
public static boolean checkForDuplicates(int[] array, int enteredValue){
   for(int i=0;i<array.length;i++){
       if(array[i] == enteredValue)
           return true;
   }
   return false;
}

Every time a number is entered, you'll check if its in the proper range (10 to 100) as you're doing now, then call this method to see if your array has duplicates.

If the number entered doesn't already exist, you'll print out all stored numbers. Let's create another method for this to keep things clean.

public static void printArray(int[] ary, int enteredValues){
    for(int i=0;i<enteredValues;i++){
        System.out.print(ary[i]+" ");
    }
    System.out.println();
}

2 Comments

IMHO, it's a bit expensive but it works. You could have direct access with little memory overhead with @user2548635 's solution. Anyway, you have a typo in your first code block.
@ChiefTwoPencils Expensive in CPU, cheap in memory. Always have that trade-off. I'd favor this approach any day for input under 10,000 on a modern computer. Less variables, less chance duplicate arrays get out of sync. But actually if it were my problem I wouldn't be using arrays ;). I'd use an existing set implementation.
0

Use a set, after taking the input add it to the set using set.add(). It will return you a boolean based on whether it was already present or not. Check the result and display appropriate message. Do some homework man...:)

1 Comment

This is the correct way to do it, but the question explicitly states that an array is not being used as the storage mechanism. If the question is edited to no longer include that as an explicit requirement, this gets my upvote.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.