Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java在循环中选择变量_Java_Variables_Loops - Fatal编程技术网

Java在循环中选择变量

Java在循环中选择变量,java,variables,loops,Java,Variables,Loops,我想知道是否有一种更有效的方法来选择循环中的变量。下面的代码我所拥有的工作,但我想有一个更好的方法来做,如果可能的话 Map<Character, Character> axes = new HashMap<Character, Character>(); (...) for (int w = 0; w < image.getWidth(); w++) { for (int h = 0; h < image.getHeight(); h++) {

我想知道是否有一种更有效的方法来选择循环中的变量。下面的代码我所拥有的工作,但我想有一个更好的方法来做,如果可能的话

Map<Character, Character> axes = new HashMap<Character, Character>();

(...)

for (int w = 0; w < image.getWidth(); w++) {
    for (int h = 0; h < image.getHeight(); h++) {
        for (int d = 0; d < depth; d++) {
            int x = axes.get('x') == 'w' ? w : (axes.get('x') == 'h' ? h : d);
            int y = axes.get('y') == 'w' ? w : (axes.get('y') == 'h' ? h : d);
            int z = axes.get('z') == 'w' ? w : (axes.get('z') == 'h' ? h : d);

            (...)

        }
    }
}
Map axes=newhashmap();
(...)
对于(int w=0;w

在上面的内容中,我需要将图像的某些坐标指定给具有深度的三维坐标,但它使用的边会根据其面对的方向而变化。有没有更快的方法来执行代码而不必进行单独的循环?

您可以移动
轴。从循环中获取(…)
调用。那应该足够快了。如果速度仍然太慢,则在循环外部执行逻辑,在内部循环中执行切换:

final char xaxis = axes.get('x');
final char yaxis = axes.get('y');
final char zaxis = axes.get('z');
final int  mode  = xaxis == 'x' && yaxix == 'y' ? 1 : ....
然后

           switch (mode) {
             case 1: x = w; y = h; z = d; break;
             case 2: ...
           }
           // work with x,y,z

您可以尝试以下方法:

int[] coords = new int[3];
int width = image.getWidth();
int height = image.getHeight();
for (coords[0] = 0; coords[0] < width; ++coords[0])
{
    for (coords[1] = 0; coords[1] < height; ++coords[1])
    {
        for (coords[2] = 0; coords[2] < depth; ++coords[2])
        {
            int x = coords[x_idx];
            int y = coords[y_idx];
            int z = coords[z_idx];
            …
        }
    }
}
int[]coords=newint[3];
int width=image.getWidth();
int height=image.getHeight();
对于(坐标[0]=0;坐标[0]
+1,我在这里写了同样的解决方案(你只是忘了告诉
x_idx=axes.get('x')='w'?0:(axes.get('x')='h'?1:2);
在循环之前有大量额外的数组访问,这实际上可能会减慢整个过程,因为必须始终进行索引绑定检查。