【问题标题】:Java for loop not running full loopJava for 循环未运行完整循环
【发布时间】:2015-08-22 02:25:52
【问题描述】:

我不确定这是否是我的 for 循环或矩形位置的问题,但我设置了一个断点并使用调试绘图来绘制矩形,它们似乎是正确的。

public void onAction(String name, boolean value, float tpf) {
     if(name.equals("ShowInventory")){
        if(!value){
            if(Statics.s_ShowInventory == true){
                Statics.s_ShowInventory = false;
            }else{
                Statics.s_ShowInventory = true;
            }
        }
    }

     if(name.equals("RightClick") && Statics.s_ShowInventory == true){
         Vector2f mousePos = screen.getMouseXY();
        for(int i = 0; i < 40; i++)
        {
            if(Main.inventory.inventorySlots[i].rect.Contains(mousePos)){
                System.out.println(Main.inventory.inventorySlots[i].slotNumber);
            }
        }
     }
}

正在发生的事情是,唯一写入控制台的矩形是第一个矩形。我想要发生的是每次右键单击为真并且布尔值为真时,循环遍历矩形列表并找出哪个包含mousePos。单击矩形时,控制台中仅显示“0”,因此我知道我没有得到任何其他库存槽编号重叠。

可能发生的另一件事是循环可能没有完全运行,这将是我的 click 方法中的一个问题。

   public float x;
public float y;
public float width;
public float height;

public Rect(float x, float y, float width, float height){
    this.x = x; 
    this.y = y;
    this.width = width;
    this.height = height;
}

public boolean Contains(Vector2f pos){
    if(pos.x > x && pos.x < width && pos.y < height && pos.y > y){
        return true;
    }
    else
        return false;
}


           Element e = createInventorySlot(i, x, y);
            inventoryElements[i] = e;
            inventorySlots[i] = new InventorySlot(i, 0, "empty", new Rect(inventoryElements[i].getPosition().x, inventoryElements[i].getPosition().y, iconSize, iconSize));
            e.setToolTipText(inventorySlots[i].itemName + " : " + inventorySlots[i].slotNumber + " : " + inventorySlots[i].quantity);
    inventory.addChild(e);

【问题讨论】:

  • 不太清楚你在问什么 - 在我看来,如果这些库存槽不重叠,那么你应该只期望看到一个打印出来。
  • 我在问是否有任何突出的东西会给我带来点击时仅读取元素 [0] 的问题?如果我单击任何其他inventorySlot,控制台中不会显示任何内容。
  • 我应该改用什么?我有 Vector2 鼠标位置和一个矩形数组来检查哪个矩形包含鼠标。
  • 使用鼠标监听器。这是一个 Swing 图形用户界面吗?展示更多,告诉更多。

标签: java jmonkeyengine


【解决方案1】:

for 循环一直在循环。尝试在每个循环中打印出 if 语句的状态。

for(int i = 0; i < 40; i++)
    {
    //    if(Main.inventory.inventorySlots[i].rect.Contains(mousePos)){
    //        System.out.println(Main.inventory.inventorySlots[i].slotNumber);
    //    }

          System.out.println(Main.inventory.inventorySlots[i].rect.Contains(mousePos));
    }

“.Contains”可能有问题,而不是 for 循环。 您的“.Contains”可能只在第一个插槽中进行测试。这可以解释为什么如果鼠标在第一个插槽中它只能工作一次。还要检查尝试打印出插槽列表,以确保您没有第一个插槽的 40 个副本。

【讨论】:

  • 插槽是另一个名为 element 的类的副本,并且该元素类不包含 Rectangle 类,因此我创建了一个以便使用 Contains 方法来获取鼠标位置。不过,我会试一试。
  • 已编辑以包含 Rect 类。使用您的方法证明 Contains 在所有情况下都返回 false
  • 尝试打印出 pos.x 和 pos.y 并为 y 值测试尝试 switch 和 符号
  • 嗯,我的矩形没有正确创建...很奇怪。
  • 我把它贴在了底部。出于某种原因,即使我根据元素设置矩形,值也不相同。我不确定为什么会这样。我设置了一个断点来检查值,只有 x 值是相同的
猜你喜欢
  • 1970-01-01
  • 2014-10-07
  • 2016-11-10
  • 2019-03-06
  • 1970-01-01
  • 1970-01-01
  • 2015-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多