Solve Java Array Issue: Unique Numbers 10-100

  • Comp Sci
  • Thread starter iamjon.smith
  • Start date
  • Tags
    Array Java
In summary, the program involves creating a one-dimensional array and prompting the user to enter ten numbers between 10 and 100. If a duplicate number is entered, it is not stored in the array. After all ten numbers have been entered, the program displays the unique numbers entered by the user. The code also includes validation to ensure that only valid numbers are accepted.
  • #1
iamjon.smith
117
3
Simple Array assignment, directions as follows:

(Must be implemented using a one-dimensional array.)

Write an application that inputs ten numbers from the user, each number can be between 10 and 100, inclusive. As each number is read in determine if it is a number already entered. If it is a duplicate move on to the next number, if it is unique store the number in the array. After all ten numbers have been entered display the complete set of unique numbers that were entered

My problem:

I have created an array that accepts user input for all 10 array elements, it validates the integers to ensure they are between 10 -100, and outputs them to the screen correctly. The problem I am having is when the user inputs a duplicate number. The duplicate number needs to be dropped (preferably with an error message requesting new input) and unique numbers accepted to the array. It must output 10 unique numbers.

my code:
Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package myarray;

/**
 *
 * @author Jon and Jessica
 */
import java.util.Scanner;

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // Declare variables
        int newNumber;
        int myNumber;

     
         Scanner input = new Scanner( System.in );     // create Scanner object
        
            int[] myArray = new int[10];         // Create an array with an index of 10
            

            // Allow user to set all numbers in array
            for (int number = 0; number < myArray.length; number++){   // Initialize counter
            System.out.println("Please enter a number between 10 - 100: ");
             
            // Ask until user enters a unique number
            do{

                newNumber = input.nextInt();
                                 
                 // User friendly error message
                 if ( newNumber < 10 || newNumber > 100){           // Check to make sure user input valid number
                     System.out.println("The Number must be between 10 - 100! Let's try that again: "); // Request new number if first is negative
                     }
                
               } while ( newNumber < 10 || newNumber > 100);
                    myArray[number] = newNumber;

            }

                // Print all array elements
                for(int number = 0; number < myArray.length; number++){
                System.out.printf("The Number entered at %s is %s\n",number, myArray[number]);
                }
            
            }
       
}
 
Physics news on Phys.org
  • #2


iamjon.smith said:
Simple Array assignment, directions as follows:

(Must be implemented using a one-dimensional array.)

Write an application that inputs ten numbers from the user, each number can be between 10 and 100, inclusive. As each number is read in determine if it is a number already entered. If it is a duplicate move on to the next number, if it is unique store the number in the array. After all ten numbers have been entered display the complete set of unique numbers that were entered

My problem:

I have created an array that accepts user input for all 10 array elements, it validates the integers to ensure they are between 10 -100, and outputs them to the screen correctly. The problem I am having is when the user inputs a duplicate number. The duplicate number needs to be dropped (preferably with an error message requesting new input) and unique numbers accepted to the array. It must output 10 unique numbers.

my code:
Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package myarray;

/**
 *
 * @author Jon and Jessica
 */
import java.util.Scanner;

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // Declare variables
        int newNumber;
        int myNumber;

     
        Scanner input = new Scanner( System.in );     // create Scanner object
        
        int[] myArray = new int[10];         // Create an array with an index of 10
            

        // Allow user to set all numbers in array
        for (int number = 0; number < myArray.length; number++){   // Initialize counter
           System.out.println("Please enter a number between 10 - 100: ");
             
           // Ask until user enters a unique number
           do
           {
              newNumber = input.nextInt();
                                 
              // User friendly error message
              if ( newNumber < 10 || newNumber > 100)
              {    
                 // Check to make sure user input valid number
                 System.out.println("The Number must be between 10 - 100! Let's try that again: "); // Request new number if first is negative
              }
                
          } while ( newNumber < 10 || newNumber > 100);
         myArray[number] = newNumber;

       }

       // Print all array elements
       for(int number = 0; number < myArray.length; number++){
         System.out.printf("The Number entered at %s is %s\n",number, myArray[number]);
       }
            
    }
}

You aren't checking for duplicate entries in the array. After you input a number, you need logic that checks whether the number is already in the array. If it's there, don't try to put the input number into the array. If it isn't present, put it in the array.

BTW, I lined up your indentation to make your code easier to read. Statements that are in a code block (such as in a loop body) should all be indented at the same level, not drift here and there on the page.
 
  • #3


Thank you for the reply. I ended up using an enhanced for loop and checking for multiple entries:

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package myarray;

/**
 *
 * @author Jon and Jessica
 */
import java.util.Scanner;

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // Declare variables
       
        int newNumber;
        int[] myArray = new int[10]; // create array with 10 elements
        int[] counter = new int[11]; // create counter array
     
         Scanner input = new Scanner( System.in );     // create Scanner object
                          

            // Allow user to set all numbers in array
            for (int number = 0; number < myArray.length; number++){   // Initialize counter
            System.out.println("Please enter a number between 10 - 100: ");

           
            // Ask until user enters a unique number
            do{
                  newNumber = input.nextInt();
                  
                 // User friendly error message
                 if ( newNumber < 10 || newNumber > 100){           // Check to make sure user input valid number
                     System.out.println("The Number must be between 10 - 100! Let's try that again: "); // Request new number if first is negative
                     }
                
               } while ( newNumber < 10 || newNumber > 100);
                 // Call arrayDupeCheck method to check user input for duplicates & display error message
                 if (arrayDupeCheck(myArray, newNumber)){
                   System.out.println("You have already entered that number! Please enter replacement number: ");
                   newNumber = input.nextInt();
                 }
                // assign user input to index (number) of array
                myArray[number] = newNumber;
                }
                // Print all array elements
                for(int number = 0; number < myArray.length; number++){
                System.out.printf("The Number entered at %s is %s\n",number, myArray[number]);
                }
    }
                    // Method good with enhanced for loop to check for duplicate entries to array
                    public static boolean arrayDupeCheck(int[] array, int dupeNumber){
                    for (int number : array){
                    if (number == dupeNumber){
                    return true;
                        }
                    }
                    return false;
                }
    }

The only problem I have at this point, working past my deadline at this point, is that if the duplicate is entered right after an invalid entry (not between 10 - 100) it will throw the user error message ("Must be between 10-100) and then it will accept the duplicate number as a valid entry. How could I fix this problem?
 
  • #4


iamjon.smith said:
Thank you for the reply. I ended up using an enhanced for loop and checking for multiple entries:

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package myarray;

/**
 *
 * @author Jon and Jessica
 */
import java.util.Scanner;

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // Declare variables
       
        int newNumber;
        int[] myArray = new int[10]; // create array with 10 elements
        int[] counter = new int[11]; // create counter array
     
         Scanner input = new Scanner( System.in );     // create Scanner object
                          

            // Allow user to set all numbers in array
            for (int number = 0; number < myArray.length; number++){   // Initialize counter
            System.out.println("Please enter a number between 10 - 100: ");

           
            // Ask until user enters a unique number
            do{
                  newNumber = input.nextInt();
                  
                 // User friendly error message
                 if ( newNumber < 10 || newNumber > 100){           // Check to make sure user input valid number
                     System.out.println("The Number must be between 10 - 100! Let's try that again: "); // Request new number if first is negative
                     }
                
               } while ( newNumber < 10 || newNumber > 100);
                 // Call arrayDupeCheck method to check user input for duplicates & display error message
                 if (arrayDupeCheck(myArray, newNumber)){
                   System.out.println("You have already entered that number! Please enter replacement number: ");
                   newNumber = input.nextInt();
                 }
                // assign user input to index (number) of array
                myArray[number] = newNumber;
                }
                // Print all array elements
                for(int number = 0; number < myArray.length; number++){
                System.out.printf("The Number entered at %s is %s\n",number, myArray[number]);
                }
    }
                    // Method good with enhanced for loop to check for duplicate entries to array
                    public static boolean arrayDupeCheck(int[] array, int dupeNumber){
                    for (int number : array){
                    if (number == dupeNumber){
                    return true;
                        }
                    }
                    return false;
                }
    }

The only problem I have at this point, working past my deadline at this point, is that if the duplicate is entered right after an invalid entry (not between 10 - 100) it will throw the user error message ("Must be between 10-100) and then it will accept the duplicate number as a valid entry. How could I fix this problem?

Your program logic is somewhat flawed. The idea is to fill an array of 10 numbers, so at the outer level you need a loop that will run 10 times. Inside this loop you should have another loop that does input, checking that the current input value is between 10 and 100, inclusive, AND that the current input value isn't one that is already present in the array. If the current input value is outside the acceptable range OR it is already in the array, exit the inner loop. When you're checking to see if there is duplication, you don't need to go through the entire array - only through elements 0 through i - 1, the elements that have already been put into the array.

Your program has some extra stuff in it that should be removed - the counter array. You declared it, but its elements are never initialized, despite a comment that says they are being initialized.
 
  • #5


Ok, so I turned in the assignment and much thanks for the help. I am now continuing to work on this on my own just so I learn.

Now, on to working with this a bit more.

I forgot to take out the counter array, it was to be used, but I ended up changing to the enhanced for loop which didn't need the counter arrray to work. As for the flawed logic, I am not sure what is causing the problem:
I used a do/while loop for the array input, with an if statement to catch the invalid number. Inside the while loop is an if statement calling the dupeCheck method, which checks for duplicate numbers. So, what I have would be a do/while loop with two nested if statements to control invalid/duplicate entries.

I have now removed the extra, unused counter, but am lost as to what would complete it. I can find the missing piece.
Code:
 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package myarray;

/**
 *
 * @author Jon and Jessica
 */
import java.util.Scanner;

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // Declare variables
       
        int newNumber;
        int[] myArray = new int[10]; // create array with 10 elements
             
         Scanner input = new Scanner( System.in );     // create Scanner object
                          

            // Allow user to set all numbers in array
            for (int number = 0; number < myArray.length; number++){   // Initialize counter
            System.out.println("Please enter a number between 10 - 100: ");

           
            // Ask until user enters a unique number
            do{
                  newNumber = input.nextInt();
                  
                 // User friendly error message
                 if ( newNumber < 10 || newNumber > 100){           // Check to make sure user input valid number
                     System.out.println("The Number must be between 10 - 100! Let's try that again: "); // Request new number if first is negative
                     }
                
               } while ( newNumber < 10 || newNumber > 100);
                 // Call arrayDupeCheck method to check user input for duplicates & display error message
                 if (arrayDupeCheck(myArray, newNumber)){
                   System.out.println("You have already entered that number! Please enter replacement number: ");
                   newNumber = input.nextInt();
                 }
                // assign user input to index (number) of array
                myArray[number] = newNumber;
                }
                // Print all array elements
                for(int number = 0; number < myArray.length; number++){
                System.out.printf("The Number entered at %s is %s\n",number, myArray[number]);
                }
    }
                    // Method good with enhanced for loop to check for duplicate entries to array
                    public static boolean arrayDupeCheck(int[] array, int dupeNumber){
                    for (int number : array){
                    if (number == dupeNumber){
                    return true;
                        }
                    }
                    return false;
                }
    }
 
  • #6


I have shown you the algorithm I would use in post #4.
 
  • #7


You should also consider that fact that the user might not enter a number. For instance, what if the user enters "ten"? All they get is a cryptic error message, and your program ends.
 
  • #8


Thank you for all of the help Mark! I was still unable to find the algorithm you suggested in #4, but either way, you have done a great job helping me.

Strants, the check for "ten", or some idiot user just entering a letter to see what would happen will be included at a later date. Good lucking out though.
 

Related to Solve Java Array Issue: Unique Numbers 10-100

1. How do I solve the issue of finding unique numbers in a Java array?

To solve this issue, you can use a set data structure in Java. Sets only allow unique values, so by converting your array to a set, you can easily find the unique numbers within the range of 10-100.

2. Can I use a loop to find unique numbers in a Java array?

Yes, you can use a loop to iterate through the array and check for unique numbers. However, using a set data structure may be a more efficient solution.

3. What is the time complexity of finding unique numbers in a Java array?

The time complexity of finding unique numbers in a Java array using a set data structure is O(n), where n is the number of elements in the array. This is because sets use hash tables, which have a constant lookup time.

4. How do I handle duplicates when finding unique numbers in a Java array?

If you want to exclude duplicates from your set of unique numbers, you can use a conditional statement to check for duplicates before adding them to the set. Alternatively, you can use a set that allows duplicates, such as a multiset.

5. What if my Java array contains non-numeric values?

If your Java array contains non-numeric values, you can either filter them out before finding unique numbers, or you can modify your code to handle non-numeric values. This could involve converting them to integers or skipping over them during the loop.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
18
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
9
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
12
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
5
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
3K
  • Programming and Computer Science
Replies
8
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
6
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
8
Views
3K
Back
Top