[Solved] Getting an array element to “disappear” when selected


Fill 2 arrays of length 26

  • One to keep track of the opened boxes (booleans, true means opened)
  • One to keep track of the values in the boxes

Here is a quick example. It is an infinite loop, so you’ll need to come up with the exit condition

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    Random rand = new Random();

    // boxes array
    Boolean[] boxes = new Boolean[26];
    Arrays.fill(boxes, false);

    // values array
    int[] values = new int[26];
    for(int i=0; i<values.length; i++) {
      values[i] = rand.nextInt(10);
    }

    int box;
    while(true) {
      for(int i=0; i<boxes.length; i++) {
        // if opened print the value, if closed print the box
        String boxString = boxes[i] ? " "+values[i]+"  " : "["+(i+1)+"] ";
        System.out.print(boxString);
      }
      System.out.println("\nChoose a box");
      box = sc.nextInt();
      boxes[box-1] = true;
    }
  }

This prints

[1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20] [21] [22] [23] [24] [25] [26] 
Choose a box
3
[1] [2]  4  [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20] [21] [22] [23] [24] [25] [26] 
Choose a box
1
 9  [2]  4  [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20] [21] [22] [23] [24] [25] [26] 
Choose a box
26
 9  [2]  4  [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20] [21] [22] [23] [24] [25]  7  
Choose a box

EDIT:

String boxString = boxes[i] ? " "+values[i]+"  " : "["+(i+1)+"] ";

is a short way to write an if statement with a return value, it is the same as:

String boxString;
if(boxes[i])
  boxString = " "+values[i]+"  ";
else
  boxString = "["+(i+1)+"] ";

Syntax:

String boxString = condition ? value if condition is true : value if condition is false;

1

solved Getting an array element to “disappear” when selected