前編
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import static java.lang.System.*;
public class RelativesTester
{
public static void main( String args[] ) throws IOException
{
Scanner in = new Scanner(new File("Relatives.dat"));
int z = in.nextInt();
for(int x = 0; x<z;x++)
{
String n = in.nextLine();
Relatives a = new Relatives();
a.setPersonRelative(n);
System.out.println (a);
}
}
}
第二部
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Scanner;
import static java.lang.System.*;
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(" ");
String person = personRelative[0];
String relative = personRelative[1];
if(map.containsKey(person))
{
map.get(person).add(relative);
}
else
{
Set<String> relatives = new TreeSet<String>();
relatives.add(relative);
map.put(person,relatives);
}
}
/**
* Returns the String version of the set containing person's relatives
* (see last line of sample output)
* @param person the person whose relative set should be returned as a String
* @param the string version of person's relative set
*/
public String getRelatives(String person)
{
String s = "";
s+=(person);
s+=(" is related to ");
for(String relative : map.get(person))
{
s+=(relative);
s+=(' ');
}
return s;
}
/**
* returns the String version of the entire map listing each key person and all of
* their relatives
* (see sample output except last line)
*/
public String toString()
{
String output="";
return output;
}
}
datファイル
14
Jim Sally
Fred Alice
Jim Tom
Jim Tammy
Bob John
Dot Fred
Dot Tom
Dot Chuck
Bob Tom
Fred James
Timmy Amanda
Almas Brian
Elton Linh
Dot Jason
Dot
outofbounds 例外というエラーが表示されますが、その理由や意味がわかりません。私はまだ toString を終えていませんが、それが問題なのですか、それとも何か他のことですか? それが toString の場合、次のようにフォーマットするにはどうすればよいですか
Bob is related to John Tom
Dot is related to Chuck Fred Jason Tom
Elton is related to Linh
私はそれを働かせることができません