I have a 3x3 array of text fields whose values get transferred to an int array. I need to make sure that integers 1-9 each occur once within the int array. Any ideas on how to go about that? I could do it by verifying that every int is between 1 and 9 and then adding them up to see if the total is 45. There are two problems with that: First, eventually I'm going to add code to highlight the first invalid number found (whether it be a duplicate or an int other than 1-9) so I'll need to know which number is invalid. Second, I know there's got to be a much easier way than that. Any ideas? Thanks in advance!

4
Contributors
5
Replies
6
Views
6 Years
Discussion Span
Last Post by Ezzaral

I guess you could have an array that holds 1-9. and, each time a number is typed in your text fields, as long as it is between 1 and 9, inclusive, you set the corresponding value in the initial array I suggested to 0. Every time a user types in a number, you would first have to check if the number is still on the array (indicating it hasn't still been typed), and if it is, receive it as input, otherwise, refuse it. hope this helps.

Edited by bibiki: n/a

Or the array could be boolean vs int and set it true if the number has been used.

I guess... except that the array's indices would be between 0 and 8, so some arithmetic would be necessary, or am I missing something?

Any array can have indices from 0-9, int and boolean.

You get an int from 0-9 then:

``````if (booleanArray[ix})
// number is used ...
else
booleanArray[ix] = true;  // remember that this number is used``````

Edited by NormR1: n/a

Perhaps you could use a Set of 1-9 and remove each entry as you encounter it. The remove() method returns a boolean to indicate if the element was in the set, so invalid numbers or repeats would be detected easily and you would also be able to verify that you had all 1-9 if the set is empty.

``Set<Integer> s = new HashSet<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9));``

Edited by Ezzaral: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.