Reputation: 37
I am beginner to Java, so I am learning through experimentation. I wanted to create a class where it would take a type of ride as a String and number of riders as an Integer. I decided to use Map because it would allow me to keep together a ride type with its pertinent # of individuals.
//How many attendants in total
System.out.println("How many attendents today?: ");
int numberOfAttendents = Integer.parseInt(bf.readLine());
System.out.println("Total number of attendents: " + numberOfAttendents);
Map<String, Integer> typeOfRide = new HashMap<String, Integer>();
boolean run = true;
final String counterEnd = "stop";
while(run)
{
System.out.println("What type of ride?: ");
String nameOfType = bf.readLine();
if(nameOfType.equalsIgnoreCase(counterEnd))
{
run = false;
}
else
{
System.out.println("Number of riders?: ");
Integer numberPerType = Integer.parseInt(bf.readLine());
typeOfRide.put(nameOfType, numberPerType);
}
}
So the above part compiles with no problem. However when I try to add the number of riders per ride type, I am having some difficulty try to come up with a way. I understand the enhanced for loop I used is for arrays and not for map.
//Adding individual entries of same ride
for(Integer i: typeOfRide)
{
int sum = 0;
System.out.println("Which ride type?: ");
String typeNumber = bf.readLine();
sum = sum + typeOfRide.get(typeNumber);
System.out.println("Total number of riders per" + typeNumber + ":" + sum);
}
So if y'all can suggest a method to get the sum, I would appreciate. Thanks!
Upvotes: 1
Views: 3060
Reputation: 13351
typeOfRide
is a Map, which does not implement iterable, which should give you a compilation error above.
For the loop, you will probably want to use either typeOfRide.entrySet()
, typeOfRide.keySet()
or typeOfRide.values()
In addition to vinodadhikary's answer about moving the int sum = 0;
to above the for-loop, looping on this should solve it.
Upvotes: 1
Reputation: 38645
You are initializing sum
inside the loop which causes the value of sum
to be typeOfRide.get(typeNumber)
. Move the line int sum = 0;
above the for
loop.
Upvotes: 2