我正在编写一个循环,该循环将数字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]);
    }
  }
}

最佳答案

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]);
}

09-11 10:52