创建实例并从枚举中调用方法JAVA

时间:2014-06-07 18:01:25

标签: java enums

我有一个enum类Direction有一个方法,它被允许返回一个随机方向(北,东,南或西),我想从同一个包中另一个类的main方法调用它。但是我无法做到这一点,因为我无法从静态方法中调用非静态方法。所以我尝试创建一个enum类Direction的实例,但到目前为止我记得所有枚举类型的构造函数都是私有的,它们不能被实例化。那么我如何从枚举类中调用一个方法。

package battleship;

public enum Direction {
/**
 * The North Direction (where y decreases)
 */
NORTH,

/**
 * The East Direction (where x increases)
 */
EAST,

/**
 * The South Direction (where y increases)
 */
SOUTH,

/**
 * The West Direction (where x decreases)
 */
WEST;

Direction getDirection() {
    Direction direction = null;
    int dir = (int) (Math.random() * 4);
    switch (dir) {
    case 0: direction = Direction.NORTH;  break;
    case 1: direction = Direction.EAST;  break;
    case 2: direction = Direction.WEST;  break;
    case 3: direction = Direction.SOUTH;  break;
    }
    return direction;
}
}

package battleship;

public class SeaTest {
public static void main(String[] args) {
    Sea sea = new Sea(10, 10);
    Direction dir = new Direction();

    sea.addShip(ShipType.MINESWEEPER, dir.getDirection(), (int)(Math.random() * 11), (int)(Math.random() * 11));
    sea.addShip(ShipType.MINESWEEPER, dir.getDirection(), (int)(Math.random() * 11), (int)(Math.random() * 11));
    sea.addShip(ShipType.MINESWEEPER, dir.getDirection(), (int)(Math.random() * 11), (int)(Math.random() * 11));
    sea.addShip(ShipType.MINESWEEPER, dir.getDirection(), (int)(Math.random() * 11), (int)(Math.random() * 11));
    sea.addShip(ShipType.BATTLECRUISER, dir.getDirection(), (int)(Math.random() * 11), (int)(Math.random() * 11));
    sea.addShip(ShipType.BATTLECRUISER, dir.getDirection(), (int)(Math.random() * 11), (int)(Math.random() * 11));
    sea.addShip(ShipType.BATTLECRUISER, dir.getDirection(), (int)(Math.random() * 11), (int)(Math.random() * 11));
    sea.addShip(ShipType.DREADNOUGHT, dir.getDirection(), (int)(Math.random() * 11), (int)(Math.random() * 11));
    sea.addShip(ShipType.DREADNOUGHT, dir.getDirection(), (int)(Math.random() * 11), (int)(Math.random() * 11));
    sea.addShip(ShipType.FLATTOP, dir.getDirection(), (int)(Math.random() * 11), (int)(Math.random() * 11));

    System.out.println(sea.toStringWithShips());

    while (sea.allShipsSunk() != true) {
        int x = (int) (Math.random() * 11);
        int y = (int) (Math.random() * 11);
        int bombCount = 0;
        sea.dropBomb(x, y);
        bombCount++;
        System.out.println("Bomb number: " + bombCount + " on coordinates "
                + x + "," + y + ". Hit Target: " + sea.dropBomb(x,    y));
    }

    System.out.println(sea.toStringWithBombs());
}
}

1 个答案:

答案 0 :(得分:0)

您可以使用Direction.NORTH.getDirection()(或任何其他枚举值而非NORTH)调用该方法