第一部分
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;
}
}
数据文件
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
我收到一个错误提示超出范围异常并且不知道为什么或这意味着什么?我还没有完成 toString 是这个问题还是别的什么?如果它是 toString 我该如何格式化它看起来像这样
Bob is related to John Tom
Dot is related to Chuck Fred Jason Tom
Elton is related to Linh
我无法让它工作