我正在编写一个循环,将数字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]);
}
}
}
答案 0 :(得分: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]);
}
答案 1 :(得分:3)
在实际代码中这是一个可怕的想法。如果您只需要一个hackish解决方案,只需在递增索引计数器时循环,访问每个数组元素,直到超出界限
// 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));