-5

I am trying to ask a user to input elements, but if the user inputs a repeated element my method should return false. So far this is what I have... Thank you in advance!

public boolean setGuess(int index, int value) // required by instructor
{ 
    int [] guesses = new int[countVal]; //countVal is array length
    for (int i = 0; i < guesses.length; i++)
        for (int j = 0; j < i; j++)
        {
            if (guesses[i] == guesses[j])
                return false;
        }
    return true;
}
zellus
  • 9,617
  • 5
  • 39
  • 56

3 Answers3

2
boolean hasRepeatedElement = new HashSet(Arrays.asList(arr)).size() == arr.length;
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
0

Although you did not ask a real question, it is fairly obvious you are going to get into trouble because you allocated an array of integers but never filled them with anything. Then you starting looking for duplicates.

If your question was "this doesn't work for me" then this is one place to look.

Another is that you have a method called setGuess which does not at all sound like a method that should look for duplicates. The fact that it is called setGuess and is "required by instructor" means there is much more to this assignment than you have in your question.

Consider expanding the question, then I can withdraw this answer, which was too long for a comment....

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
0

More over in the same Question 1. in place of guesses.length u can use countVal.
2. Whats the use of "int index, int value" parameters, you are not using in the method. 3. declaring guesses[] will will have only 0 at all the indexes, so "guesses [i] == guesses[j]" has no meaning.

Try to answer all the above points, will help you code better.

Swagatika
  • 3,376
  • 6
  • 30
  • 39