Click here to Skip to main content
15,905,563 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My problem is I got the numbers displayed correctly, but I don't know how to display all of them, and I can't display duplicate numbers. This is the problem.

Use a one-dimensional array to solve the following program. Write an
application that inputs six numbers [Keep the numbers in an array]. The numbers can be
between 20 and 200, inclusive. When a number is entered, display the number only if it
is not a duplicate of a number already entered. Provide for the worst case in which all
six numbers are different. Display the complete set of unique values input after the user enters each new value.

Enter number: 5 //prompt
Number must be between 20 and 200 //display warning message if it is necessary
Enter number: 21 // prompt again
21 //display the number kept in the array
Enter number: 32 // prompt again
21 32 //display all entered numbers in the array each time after a new number is
added
Enter number: 23
21 32 23
Enter number: 23
23 has already been entered //display message if a duplicate number is entered
Enter number: 33
21 32 23 33

What I have tried:

Here is my code so far
import java.util.Scanner; //program uses Scanner

public class Duplicate {
	public static void main (String [] args) {
		
		//declare an array with 5 elements
		int myArray[] = new int[6];
		//int counter = 0;
		//boolean duplicate = false;
		
		Scanner input = new Scanner(System.in);
		while(counter < myArray.length){
			System.out.print("Enter an integer between 20 and 200: ");
			int number = input.nextInt();
						
			if (number >= 20 && number <= 200)
			{
				++counter;
				myArray[counter] = number;
				System.out.printf("%d%n", myArray[counter]);
			}
		else{
			System.out.println("Error: You did not enter a number between 20 and 200");
			}
		}
	}
}
Posted
Updated 12-Oct-18 22:00pm

1 solution

Start by initialising the array so that each item contains a value that is outside the range of valid numbers. In this case -1 would be a reasonable choice. Each time a new number is entered you need to check that it is in the valid range, but also that it is not already in your array. Once you have done that, then add it to the next 'empty' element of the array and print the valid numbers of the array.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900