使用异常处理分配数组值

Ste*_*lsh 3 java arrays exception

我正在编写一个循环,将数字15分配给数组中的每个元素,而不使用任何比较运算符,例如<,==,>或!=.

显然有一种方法可以使用异常处理来完成此操作.

有任何想法吗?

这是我试过的:

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]); 
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Spe*_*uce 5

Arrays.fill(intArray, 15);

在内部,此功能可能会进行比较,但它可能符合您的约束条件吗?

如果解决方案需要循环,这是另一种没有直接比较的方法:

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