0

これは私がこれまでに持っているものであり、私がやろうとしていることです。分割の両方の部分にアクセスする方法がわかりません。このコードは本当に間違っていますが、やりたいことを行う方法がわかりません(はい、学校用です)

public class Relatives
    {
        private Map<String,Set<String>> map;

        /**
         * Constructs a relatives object with an empty map
         */
        public Relatives()
        {
            map = new TreeMap<String,Set<String>>();
        }

        /**
         * adds a relationship to the map by either adding a relative to the
         * set of an existing key, or creating a new key within the map
         * @param line a string containing the key person and their relative
         */
            public void setPersonRelative(String line)
{
    String[] personRelative = line.split(" ");

    if(map.containsKey(personRelative[0]))
    {
        map.put(personRelative[0],map.get(personRelative[1])+personRelative[1]);
    }
    else
    {
        map.put(personRelative[0],personRelative[1]);
    }
}

私はその人にアクセスしてそこに現在の親戚を追加しようとしています。存在しない場合は、その親戚と一緒に新しい人を作成します

このように返されるようにフォーマットするにはどうすればよいですか

Dot is related to Chuck Fred Jason Tom
Elton is related to Linh

私はこれを持っていますが、エラーが発生します

public String getRelatives(String person)
{
    return map.keySet();
}
4

1 に答える 1

2

+=演算子を使用して Set にアイテムを追加することはできません。メソッドを使用する必要がありますadd

また、初めて使用するときにセットを作成する必要があります。

修正されたコードは次のようになります。

        String[] personRelative = line.split(" ");
        String person = personRelative[0];
        String relative = personRelative[1];
        if(map.containsKey(person))
        {
            map.get(person).add(relative);
        }
        else
        {
            Set<String> relatives = new HashSet<String>();
            relatives.add(relative);
            map.put(person,relatives);
        }
于 2013-09-26T23:39:02.300 に答える