+ 2

Hiding unselected array elements? - Java

Hi guys!. Currently I am using a 2 dimensional array with elements ranging from A1, A2, A3... to C3. When the user inputs a value (eg; A1) the program goes through the array to find a match. If the user's input matches one of the array elements then it will override that input with an x (to indicate a miss). However, the issue is, I would like my program to display the grids as so once the user has missed, for example: [x][ ][ ] [ ][ ][ ] [ ][ ][ ] rather than [x][A2][A3] [B1][B2][B3] [C1][C2][C3] I was wondering whether there was a way to take the user's input and only display the x along with the empty cells; Perhaps we can output the array normally but somehow hide/exclude the other elements that have not been selected by the user, thus only displaying x's and empty cells? https://code.sololearn.com/chk1UmVfA874/#java

8th Sep 2017, 7:31 PM
YodaCoda
YodaCoda - avatar
3 Answers
+ 9
Not sure if I got your question... but I'll give it a try: The easy way: enhanced for loop like: for (String s : myArray) { if (s.equals ("x") ) // print [x] else // print [ ] } Another way: Create your own class / type for the elements of the array with two attributes: the initial String and a bool for the right guess. Override toString of your type and check the bool attribute to return x or empty.
8th Sep 2017, 7:43 PM
Tashi N
Tashi N - avatar
+ 6
Sry, for a two dimensional array you need to nest two loops, like: for (String s[] : array) { for (String t : s) { if(t.equals("x")) System.out.println("[x]"); else System.out.println("[ ]"); } }
9th Sep 2017, 4:36 PM
Tashi N
Tashi N - avatar
+ 1
Hi, thanks for responding. I tried implementing the loop but it appears I keep getting incompatible type from: for(String s: array) Any ideas?: https://code.sololearn.com/chk1UmVfA874/#java
9th Sep 2017, 3:43 PM
YodaCoda
YodaCoda - avatar