Solve Java Array Issue: Unique Numbers 10-100

  • Context: Comp Sci 
  • Thread starter Thread starter iamjon.smith
  • Start date Start date
  • Tags Tags
    Array Java
Click For Summary

Discussion Overview

The discussion revolves around a programming assignment that requires participants to create a Java application for inputting ten unique numbers between 10 and 100 using a one-dimensional array. The focus is on handling duplicate entries and ensuring that only unique numbers are stored in the array.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Mathematical reasoning

Main Points Raised

  • One participant describes their initial implementation, which successfully validates input numbers but fails to handle duplicates properly.
  • Another participant points out the need for logic to check for duplicates before adding a number to the array, suggesting that the current code does not perform this check.
  • A later reply indicates that the original poster modified their approach by using an enhanced for loop and implementing a method to check for duplicates, although the details of this implementation are not fully provided.
  • There is a mention of improving code readability through better indentation, which some participants agree is important for clarity.

Areas of Agreement / Disagreement

Participants generally agree on the importance of checking for duplicates in the array, but the specific implementations and approaches to achieve this remain contested. The discussion does not reach a consensus on a single solution.

Contextual Notes

Limitations include the lack of a complete implementation for the duplicate check method and the handling of user input after a duplicate is detected. The discussion does not resolve how to ensure that exactly ten unique numbers are collected, as the logic for replacing duplicates is not fully detailed.

iamjon.smith
Messages
117
Reaction score
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


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.
 


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?
 


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.
 


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;
                }
    }
 


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


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.
 


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.
 

Similar threads

  • · Replies 21 ·
Replies
21
Views
3K
  • · Replies 18 ·
Replies
18
Views
3K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 12 ·
Replies
12
Views
2K
Replies
9
Views
2K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 6 ·
Replies
6
Views
4K
  • · Replies 8 ·
Replies
8
Views
3K
  • · Replies 10 ·
Replies
10
Views
12K