I have to create a hashmap with the names I have in this text file
relationships text file:
Susan Sarandon | Tom Hanks : Cloud Atlas Tom Hanks | Kevin Bacon : Apollo 13 Leonardo Dicaprio | Kevin Bacon : This Boy's Life Robert De Niro | Kevin Bacon : This Boy's Life Barack Obama | Tom Hanks : the Road We've Traveled Helen Keller | Katharine Cornell : Helen Keller in Her Story Katharine Cornell | Helen Hayes : Stage Door Canteen Helen Hayes | John Laughlin : Murder with Mirrors John Laughlin | Kevin Bacon : Footloose Mark Zuckerberg | Joe Lipari : Terms and Conditions May Apply Joe Lipari | Welker White : Eat Pray Love Welker White | Kevin Bacon : Lemon Sky
This is the program I have now:
public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("relationships")); HashMap<String, String> relationships = new HashMap<String, String>(); while (input.hasNextLine()) { String[] columns = input.nextLine().split(" "); relationships.put(columns[0], columns[1]); } System.out.println(relationships); }
This is the output:
{Leonardo=Dicaprio, Katharine=Cornell, Joe=Lipari, Tom=Hanks, Robert=De, Susan=Sarandon, John=Laughlin, Mark=Zuckerberg, Barack=Obama, Welker=White, Helen=Hayes}
Does anyone know how to fix this please? Also how to seperate them so it actually looks like a list?
EDIT
I think you would just change your line:
String[] columns = input.nextLine().split(" ");
to:
String[] columns = input.nextLine().split(Pattern.quote(" | "));
Then column[0]
would be the name on the left, and column[1]
would be the name and movie title on the right.
Note that you'll need to import java.util.regex.Pattern;
to do this
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.