2014-06-07 42 views
-1

我有一個枚舉類的方法,其中一個方法用於返回一個隨機方向(North,East,South或West),我想從main另一個類在同一個包中的方法。但是我不能這樣做,因爲我無法從靜態方法調用非靜態方法。所以我嘗試創建一個枚舉類Direction的實例,但到目前爲止,我還記得所有枚舉類型的構造函數都是私有的,它們不能實例化。所以我如何支持從一個枚舉類調用一個方法。創建一個實例並從一個枚舉中調用方法,JAVA

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()); 
} 
} 
+3

你爲什麼不進行枚舉的方法靜態? –

+0

每次使用時都不會產生相同的方向? – user3626180

+1

爲什麼呢? 'static'表示它是一個類級別的方法而不是實例級別的方法,而不是該方法的返回值不會更改。 – JonK

回答

0

您可以致電與Direction.NORTH.getDirection()方法(或任何其他枚舉值,而不是NORTH

相關問題