【问题标题】:checking an array java检查数组java
【发布时间】:2015-11-17 14:23:20
【问题描述】:

我正在使用像地图这样的二维数组,我有一个设定点 x 和 y,我需要检查周围区域 (+1) 中的三个对象,食物、对象和空间。我想过使用 map[x+1][y+1] 如下所示,但是我必须多次重复此状态。

if (map[x+1][y+1] == Item.O)
{
    System.out.println("Object is in the way.");
}

if (map[x+1][y+1] == Item.F)
{
    System.out.println("Food is in the way.");
}

还有其他方法可以做到这一点,我知道有一个 switch 语句,但我认为这不会起作用。任何帮助将不胜感激:)

【问题讨论】:

  • Itemenum?
  • 是的,抱歉忘记添加了。
  • 看起来你只需要一个嵌套的 for 循环,从 x-1 到 x+1 和 y-1 到 y+1,只要确保跳过 (x, y) 如果需要的话
  • 你想做什么?使用一个循环?
  • 是的,这可能是最好的选择,我只是想把它写得比多个 If 语句更好。

标签: java arrays if-statement switch-statement


【解决方案1】:

假设Itemenum,您确实可以使用switch 语句:

switch(map[x+1][y+1]) {
   case Item.O : System.out.println("Object is in the way."); break;
   case Item.F : System.out.println("Food is in the way."); break;
   ...
}

但是,更灵活的解决方案不是在数组中存储enum,而是实现提供所需方法的通用接口的真实对象。然后实现不同的类来实现对象的不同行为。

您的类层次结构可能如下所示:

interface PrintText {
    void printText();
}

class Food implements PrintText {
    public void printText() {
       System.out.println("Food is in the way.");
    }
}

class SomeObject implements PrintText {
    public void printText() {
       System.out.println("Object is in the way.");
    }
}

然后你可以像这样初始化你的数组:

// initialize array
PrintText[][] map = new PrintText[WIDTH][HEIGHT];
map[0][0] = new Food();
map[0][1] = new SomeObject();
...

稍后调用这样的方法,没有任何 switchif 语句 - 多态会处理它:

// call the method
map[x+1][y+1].printText();

附带说明,不要使用原始数组。请改用 ArrayList 之类的集合类。

【讨论】:

  • 这个解决方案很好。我也认为他将使用该方法进行碰撞检查,因此返回布尔值是个好主意。
  • 谢谢,枚举和项目一直很痛苦,我看看如何将它添加到我的代码中:)
  • 如果有帮助很高兴 :) 您的问题只是 调用 使用多态性通过一些通用接口实现不同类中 Food 和其他对象的不同行为 - 这样,您以后可以随时添加其他对象,对现有代码的影响很小
猜你喜欢
  • 1970-01-01
  • 2023-03-27
  • 2016-12-21
  • 2019-01-06
  • 2016-11-07
  • 1970-01-01
  • 1970-01-01
  • 2016-07-23
  • 2012-10-05
相关资源
最近更新 更多