2

首先这是一项任务,所以我更多的是寻求帮助,然后是编码答案(不想作弊!)。我的任务是创建一个程序来处理车站的火车/铁路网络。我坚持的部分添加了站点、它们的连接,并将这些连接作为字符串数组列表返回。我已经在下面包含了到目前为止的代码,以及作业的摘录(与我现在正在讨论的部分相关)。我整个周末都在努力解决这个问题,所以任何帮助都将不胜感激。

这只是我需要编辑的接口的实现,“MyNetwork”类。我只是觉得我一直在兜圈子,甚至可能没有右脚下车?

从任务中;

创建一个实现 Network 接口的 MyNetwork 类。

此类的 getConnections 方法应返回一个数组,该数组仅包含那些直接连接到 fromStation 参数的站。提示 1:您可以使用 HashMap 来执行此操作,键是字符串(表示站点),值是字符串的 ArrayLists(表示有直接连接的站点)。

提示 2:虽然 getConnections 方法返回一个字符串数组,但 HashMap 中的值最好是字符串的 ArrayLists

接口;

public interface Network {

    /**
     * Add a station to the network.
     * @param station The station to be added.
     */
    public void addStation(String station);

    /**
     * Add a direct connection from one station to another.
     * @pre both fromStation and toStation have already been added by the method
     * addStation.
     * @param fromStation The station from which the connection begins. 
     * @param toStation The station at which the connection ends.
     */
    public void addConnection(String fromStation, String toStation);

    /**
     * Get a list of all stations directly connected to a given station.
     * @pre fromStation has been added to the network by the method addStation.
     * @param fromStation
     * @return A list of all the stations to which there is a direct connection
     * from fromStation. 
     */
    public String[] getConnections(String fromStation);

    /**
     * Search for a station in the network.
     * @param station Station to be searched for,
     * @return true if the Station exists in the network, false otherwise.
     */
    public boolean hasStation(String station);

    /**
     * Get all stations in the network.
     * @return An array containing all the stations in the network, with no
     * duplicates.
     */
    public String[] getStations();

实施:

public class MyNetwork implements Network {

    @Override
    public void addStation(String station) {

        ArrayList<String> Stations = new ArrayList<>();
        Stations.add(station);
    }

    @Override
    public void addConnection(String fromStation, String toStation) {

        Map<String,String> Connections = new HashMap<>();
        Connections.put(fromStation, toStation);
    }

    @Override
    public String[] getConnections(String fromStation) {
        return null; // dummy value!

    }

    @Override
    public boolean hasStation(String station) {
        return false; // dummy value!
    }

    @Override
    public String[] getStations() {
        return null; // dummy value!
    }
}
4

1 回答 1

0

您的网络需要有一个状态,使用一个或多个实例字段。

照原样,它没有任何状态。每个方法都创建一个 List 或 Map 类型的局部变量,向该 List 或 Map 添加一些内容,然后返回。因此 List 或 Map 直接超出范围并被垃圾收集。

private Map<String, List<String>> stations = new HashMap<>();

// now all your methods should use the above map.

请参阅http://docs.oracle.com/javase/tutorial/java/javaOO/classes.html

于 2014-02-02T15:06:36.330 回答