- #1
Quincy
- 228
- 0
Code:
import java.util.*;
import java.io.*;
public class Friend
{
private static int id;
private static double lat;
private static double lon;
public Friend(int id, double lat, double lon)
{
this.id = id;
this.lat = lat;
this.lon = lon;
}
.
.
.
.
public void print()
{
System.out.println(this.id + " " + this.lat + " " + this.lon);
}
public static void main(String[] args)
{
File file = new File("small_world.txt");
try {
Scanner scan = new Scanner(file);
HashMap<Integer,Friend> friend_list = new HashMap<Integer,Friend>();
int id_number = 0;
while(scan.hasNext())
{
id_number = scan.nextInt();
Friend friend = new Friend(id_number, scan.nextDouble(),scan.nextDouble());
friend_list.put(id_number, friend);
}
for (Integer key : friend_list.keySet())
{
System.out.println(key);
friend_list.get(key).print();
}
}
catch (FileNotFoundException e)
{
System.out.print(e);
}
}
}
The output is:
1
5 79.99 179.99
2
5 79.99 179.99
3
5 79.99 179.99
4
5 79.99 179.99
5
5 79.99 179.99
It's supposed to be:
1
1 0.0 0.0
2
2 10.1 -10.1
3
3 -12.2 12.2
4
4 38.3 38.3
5
5 79.99 179.99
The input file is a text file containing:
1 0.0 0.0
2 10.1 -10.1
3 -12.2 12.2
4 38.3 38.3
5 79.99 179.99
Why are all the values for each key in the HashMap the same as the last value that was put into it? I've noticed it's only like that for the values but not the keys, the keys all in proper order. How do I fix this problem?