2

わかりましたので、ここで私がしなければならないことは次のとおりです。

渡さListれた を個々の行に分割し、区切り文字を使用してそれらの行を分割し、それらの部分を に追加しMapます。

私のコード:

public GrammarSolver(List<String> rules) {
    if(rules == null || rules.size() == 0) {
        throw new IllegalArgumentException();
    }
    Map<String, String> rulesMap = new HashMap<String, String>();
    Iterator<String> i = rules.iterator();
    while(i.hasNext()) {
        String rule = i.next(); // store a line from 'rules' List
        String[] parts = rule.split("::="); // split the line into non-terminal and terminal
        rulesMap.put(parts[0], parts[1]); // Put the two parts into the map
    }
    // TODO: exception when duplicate key in map
}

すべてが正常に機能しますが、私の割り当てでは、行のキーが重複している (複数回発生している) 場合は例外をスローする必要があることが示されています。

私が理解していることから、キーは一意にしかできないので、ここで何が欠けていますか?

4

3 に答える 3

1

例外を行に追加するだけです

rulesMap.put(parts[0], parts[1]); // Put the two parts into the map

お気に入り

// Put the two parts into the map
if((String existing = rulesMap.put(parts[0], parts[1])) != null) 
      throw new IllegalStateException(
             "duplicated key " + parts[0] 
             + " with value " + existing + " overwritten by " + parts[1]
于 2013-01-28T06:50:42.477 に答える
0

以下のように書くことができます。

while(i.hasNext()) {
    String rule = i.next(); // store a line from 'rules' List
    String[] parts = rule.split("::="); // split the line into non-terminal and terminal
    if(rulesMap.containsKey(parts[0]){
        throw New Excpetion(...);
    }else{
        rulesMap.put(parts[0], parts[1]); // Put the two parts into the map
    }

}
于 2013-01-28T01:34:10.453 に答える