遍历两个数组的元素,就像它们是有序对一样

时间:2018-04-08 02:39:44

标签: java arrays

我希望它通过两个数组作为有序对(x,y)

def comparison(a, b):
    return 2 if a > b else 1 if a == b else -1

......等等

(xcord[0],ycord[0])
(xcord[1],ycord[1])
(xcord[2],ycord[2])

它遍历数组中的每个项目但重复xcord和ycord。我没看到什么?

2 个答案:

答案 0 :(得分:5)

你使用了两个循环。如果您希望值处于锁步状态,那么您只需要一个循环(和索引)。为了清楚起见,我会使用除xy之外的其他索引。像,

public void makeActors() {
    for (int i = 0; i < 46; i++) {
        Box box = new Box();
        addObject(box, xcord[i], ycord[i]);
    }
}

,在Java 8+中,IntStream喜欢

IntStream.range(0, 46).forEachOrdered(i -> addObject(new Box(), xcord[i], ycord[i]));

答案 1 :(得分:1)

不需要第二个for循环,如果您只想从两个不同的数组中获取x和y坐标,则第一个循环应该用于此目的。考虑到两个阵列中的元素数量相同,这将起作用。

public int[] xcord = {74,177,288,27,132,479,144,408,19,80,264,380,406,491,18,85,165,206,296,106,49,25,13,78,89,145,138,167,221,234,245,371,449,347,299,379,440,291,462,393,282,338,448,318,398,456};
public int[] ycord = {11,26,41,58,54,71,99,83,121,152,124,113,129,152,214,227,187,206,191,262,276,343,472,407,447,336,458,416,470,334,270,182,185,227,294,276,302,379,356,402,438,417,427,481,475,480};

public void makeActors(){
    for(int x=0;x<46;x++){
        Box box = new Box();
        addObject(box,xcord[x],ycord[x]);
    }
}