Reputation: 23
public static void main(String[] args) throws FileNotFoundException {
double agentID;
String type;
double price;
Set<String> types = new TreeSet<String>();
Map<Double, Double> agents = new TreeMap<Double, Double>();
Scanner console = new Scanner(System.in);
String propertyID;
double totalPrice = 0;
System.out.print ("Please enter file name: ");
String inputFileName = console.next();
File inputFile = new File(inputFileName);
Scanner in = new Scanner(inputFile);
while (in.hasNextLine()) {
propertyID = in.next();
type = in.next();
price = in.nextDouble();
agentID = in.nextDouble();
type = type.toUpperCase();
types.add(type);
if (agents.containsValue(agentID)) {
agents.put(agentID, agents.get(agentID)+price);
}
else {
totalPrice = price;
agents.put(agentID, totalPrice);
}
}
in.close();
System.out.println(types);
System.out.println(agents);
}
I am trying to update map value of totalPrice
if the value in agentID
is already contained in the agents
map. When I run the program it will output the initial value assigned to the key agentID
but it will not output the totalPrice + price
. I have looked over the questions here and looked over the API Docs, but I am not making any progress. Any help would be appreciated.
Upvotes: 1
Views: 679
Reputation: 8183
in you TreeMap you have used agentID as the key and totalPirce as value, so in your code it should be
agents.containsKey(agentID)
NOT
agents.containsValue(agentID)
regards Isuru
Upvotes: 1
Reputation: 20323
You are checking value instead you should check if agent is available in the map
change
if (agents.containsValue(agentID))
to
if (agents.containsKey(agentID))
since you are using agentID
as the key here
agents.put(agentID, agents.get(agentID)+price);
Upvotes: 3
Reputation: 47665
It seems that you are trying to map the agentId with the price. So I think what you need to use is
if (agents.containsKey(agentID)) { ... }
See the official containsKey javadoc for more information.
Please try to simplify the code in your questions (remove the file reading and other unneeded info) to make it easier to determine where the problem could be.
Upvotes: 3