Assigning Array Values ​​Using Exception Handling

I am writing a loop that assigns number 15 to each element of an array without using any comparison operators such as <, ==,> or! =.

Apparently this can be done with exception handling.

Any ideas?

Here's what I've tried:

public class ArrayProblem {


public static void main(String[] args) {

    int[] arrayElements = {0,0,0,0,0};
    boolean isValid = true;
    System.out.println("Array element values before: " + arrayElements[0] + "," + arrayElements[1] + "," + arrayElements[2] + "," + arrayElements[3] + "," + arrayElements[4]);

   try
    {
       while(isValid)
       {
       throw new Exception();
       }
     }

   catch(Exception e)
    {
        System.out.println(e.getMessage());
    }

    finally
    {
        //finally block executes and assigns 15 to each array element
        arrayElements[0] = 15;
        arrayElements[1] = 15;
        arrayElements[2] = 15;
        arrayElements[3] = 15;
        arrayElements[4] = 15;
        System.out.println("New array element values are " + arrayElements[0] + "," + arrayElements[1] + "," + arrayElements[2] + "," + arrayElements[3] + "," + arrayElements[4]); 
    }
  }
}

      

+3


source to share


2 answers


Arrays.fill(intArray, 15);

Internally, this function is probably doing comparisons, but perhaps it fits your constraints?



If the solution requires a loop, here's another way without direct comparisons:

int[] array = new int[10];
int arrIdx = -1;
for (int i : array){
    arrIdx++;
    array[arrIdx]=15;
    System.out.println(array[arrIdx]);
}

      

+5


source


This is a terrible idea in real code. If you just need a hacky solution, just loop, incrementing the index counter, referring to each element of the array until you are out of scope



// prepare array, arbitrary size
Random random = new Random();
int size = random.nextInt(20);
int[] array = new int[size];

int i = 0;
// solution
try {
    for (;;)
        array[i++] = 15;
} catch (ArrayIndexOutOfBoundsException e) {
    // ignore
}

// verify
System.out.println(Arrays.toString(array));

      

+3


source







All Articles