0

Can someone help me finish this challenge?

I try to change some values of the Dictionary while iterating, but it give me an exception https://code.sololearn.com/cpAD7MyC1Hs6/?ref=app

3rd Mar 2022, 10:32 AM
Alex
Alex - avatar
3 Antworten
+ 2
That exception is kinda tricky the only thing you need to do is to use ToList() function using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sololearn { class Program { static void Main(string[] args) { int discount = Convert.ToInt32(Console.ReadLine()); Dictionary<string, int> coffee = new Dictionary<string, int>(); coffee.Add("Americano", 50); coffee.Add("Latte", 70); coffee.Add("Flat White", 60); coffee.Add("Espresso", 60); coffee.Add("Cappuccino", 80); coffee.Add("Mocha", 90); foreach(string x in coffee.Keys.ToList()) { coffee[x]-=coffee[x]*(discount/100); } } } }
3rd Mar 2022, 10:53 AM
Nima
+ 1
You accidently wrote "can" at line 7 gotta delete that line. Idk the requirement of the task, but I was wondering why you choose to modify the dictionary values when you can just print them out with some adjustments taking <discount> value into consideration. double discountPercent = 1.0 - discount / 100.0; //Console.WriteLine( discountPercent ); foreach( string key in coffee.Keys.ToArray() ) { coffee[ key ] = ( int ) ( ( double )coffee[ key ] * discountPercent ); Console.WriteLine( coffee[ key ] ); }
3rd Mar 2022, 2:52 PM
Ipang
+ 1
int discount = Convert.ToInt32(Console.ReadLine()); Dictionary<string, int> coffee = new Dictionary<string, int>(); coffee.Add("Americano", 50); coffee.Add("Latte", 70); coffee.Add("Flat White", 60); coffee.Add("Espresso", 60); coffee.Add("Cappuccino", 80); coffee.Add("Mocha", 90); foreach (KeyValuePair<string, int> entry in coffee) { Console.WriteLine(entry.Key + ": " + (entry.Value - entry.Value * discount / 100)); }
5th Mar 2022, 11:13 PM
Jackie
Jackie - avatar