I have a simple array that allows the user to enter in integer values, then prints the values of each index of the array. Is it possible to restrict each index to a different integer. In other words if the user enters in the same integer more than once it only gets stored once. Is this possible?
array = 4 array = 6 array = 6 //doesn't get stored because it exists in , try again until unique array = 8 ...etc for 20 unique values
Joined: Jan 29, 2003
With array you'd have to compare each new number to all of the existing numbers if the new one is already there. You could give the user a message and let them try again. So if they were supposed to enter 10 numbers it might take them 15 tries to get the idea that they have to be unique. Is that how you'd picture the program working?
If you're allowed to explore beyond array, look at the JavaDoc for Collection, List and Set. There is one there you'll like.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joined: Mar 13, 2004
I assume you know how to replace the for loop with a while or do loop.
In that loop, put an inner loop that searches the exising elements for a duplicate value. If one is found, set a boolean "duplicate" true and break out of the inner loop.
In the outer loop, if duplicate is true, display an error message instead of inserting an array element and incrementing the array index. Give this a try. If you have a problem, post your code and we'll help.
[ November 20, 2004: Message edited by: Mike Gershman ] [ November 20, 2004: Message edited by: Mike Gershman ]
SCJP 1.4, SCWCD in process
Joined: Nov 05, 2003
wont Sets solve ur problem...it wont allow duplicate values to be entered and if entered it would be replaced with the existing values.
"In theory, there is no difference between theory and practice. But, in practice, there is."<br /> - Jan L.A. van de Snepscheut
Joined: Nov 13, 2004
I've expanded the original program to read integer values from a file. There are 20 unique values to be stored. In the file there can be multiple instances of each integer (although they will be between 5 and 24). The program should read off all values in the file. Once all values are read it will print off the value of each index and the number of times it appears in the file.
I'm having a hard time figuring out how to record the number of times a value occurs.
Joined: Jun 09, 2003
if the values are between 5 and 24, just create an array int fileNumber = new int;
then, when you read in each number from the file
int number = [number read in from file, converted to int]; fileNumber[number]++;
at the end, loop through fileNumber looking for values > 0