有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何访问循环中的对象?

我正在尝试将对象“next”的位置值移交给下一个“next”对象。是否可以将此代码编写为循环并按n进行缩放


next.next.next.next.pos.y = next.next.next.pos.y;
next.next.next.next.pos.x = next.next.next.pos.x;
next.next.next.pos.y = next.next.pos.y;
next.next.next.pos.x = next.next.pos.x;
next.next.pos.y = next.pos.y;
next.next.pos.x = next.pos.x;
next.pos.x = pos.x;
next.pos.y = pos.y;


共 (1) 个答案

  1. # 1 楼答案

    我猜你想要这样的东西:

    while(obj.next != null) {
      obj.next.pos.x = obj.pos.x;
      obj.next.pos.y = obj.pos.y;
      obj = obj.next;
    }
    

    稍后编辑:

    对不起,我误解了你的问题

    然后,您可以使用列表来解决此问题。这不是最有效的方法,但我会努力的

    List<Obj> objs = new ArrayList<>();
    
    objs.add(obj);
    
    // Add everything to a list
    while(obj.next != null) {
        objs.add(obj.next);
        obj = obj.next;
    }
    
    // Walk the list in the reverse order
    for(i = objs.size() - 1; i > 1 ; i ) {
      objs[i].pos.x = objs[i - 1].pos.x;
      objs[i].pos.y = objs[i - 1].pos.y;
    }