在课程会议室中,我需要编写一个方法来从HashMap 退出返回随机退出,或者如果没有退出则返回null
HashMap中。
我尝试过使用迭代器并将其保存在Set中的HashMap,但没有任何作用。
public class Room
{
private String description;
private HashMap<Direction, Room> exits; // stores exits of this room.
public Set<Character> chars; // stores the characters that are in this room.
/**
* Create a room described "description". Initially, it has
* no exits. "description" is something like "a kitchen" or
* "an open court yard".
* @param description The room's description.
* Pre-condition: description is not null.
*/
public Room(String description)
{
assert description != null : "Room.Room has null description";
this.description = description;
exits = new HashMap<Direction, Room>();
chars = new HashSet<Character>();
sane();
}
/**
* Define an exit from this room.
* @param direction The direction of the exit.
* @param neighbor The room to which the exit leads.
* Pre-condition: neither direction nor neighbor are null;
* there is no room in given direction yet.
*/
public void setExit(Direction direction, Room neighbor)
{
assert direction != null : "Room.setExit gets null direction";
assert neighbor != null : "Room.setExit gets null neighbor";
assert getExit(direction) == null : "Room.setExit set for direction that has neighbor";
sane();
exits.put(direction, neighbor);
sane();
assert getExit(direction) == neighbor : "Room.setExit has wrong neighbor";
}
/**
* Return the room that is reached if we go from this room in direction
* "direction". If there is no room in that direction, return null.
* @param direction The exit's direction.
* @return The room in the given direction.
* Pre-condition: direction is not null
*/
public Room getExit(Direction direction)
{
assert direction != null : "Room.getExit has null direction";
sane();
return exits.get(direction);
}
方向:
public enum Direction
{
NORTH("north"), WEST("west"), SOUTH("south"), EAST("east");
private String name;
/**
* Constructor with parameter.
* Pre-condition: name is not null.
*/
private Direction(String name)
{
assert name != null : "Direction.Direction has null name";
this.name = name;
assert toString().equals(name) : "Direction.Direction produces wrong toString";
}
/**
* Return the direction name.
*/
public String toString()
{
return name;
}
}
任何帮助将不胜感激
答案 0 :(得分:1)
尝试将地图转换为类似的列表(在Room类中):
public Direction getRandomExit(){
List<Direction> directions = new ArrayList<Direction>(exits.keySet());
if (directions.size()==0){
return null;
}
Random rand = new Random();
int randomIndex = rand.nextInt(directions.size());
return directions.get(randomIndex);
}