这是我第一次需要使用字典。我不能覆盖item.Value,我不知道该怎么做。
编写一个程序,从标准输入行到文件末尾(EOF)每行读取一只猴子的名字,并以以下格式读取它收集的香蕉数量:
monkey_name;香蕉数
该程序以示例输出中给出的形式将猴子的名称和它们收集的香蕉数量写入标准输出,并根据猴子的名称按字典顺序升序排列!
输入:
Jambo;10
Kongo;5
Charlie;12
Jambo;10
Koko;14
Kongo;10
Jambo;5
Charlie;8 输出:
Charlie: 20
Jambo: 25
Koko: 14
Kongo: 15下面是我的代码:
string input;
string[] row = null;
IDictionary<string, int> majom = new SortedDictionary<string, int>();
int i;
bool duplicate = false;
while ((input = Console.ReadLine()) != null && input != "")
{
duplicate = false;
row = input.Split(';');
foreach(var item in majom)
{
if(item.Key == row[0])
{
duplicate = true;
i = int.Parse(row[1]);
item.Value += i; //I'm stuck at here. I dont know how am i able to modify the Value
}
}
if(!duplicate)
{
i = int.Parse(row[1]);
majom.Add(row[0], i);
}
}
foreach(var item in majom)
{
Console.WriteLine(item.Key + ": " + item.Value);
}对不起,我的英语不好,我已经尽力了。
发布于 2021-04-03 22:44:08
class Program
{
static void Main()
{
string input;
string[] row;
IDictionary<string, int> majom = new SortedDictionary<string, int>();
//int i;
//bool duplicate = false;
while ((input = Console.ReadLine()) != null && input != "")
{
//duplicate = false;
row = input.Split(';');
// Usually dictionaries have key and value
// hier are they extracted from the input
string key = row[0];
int value = int.Parse(row[1]);
// if the key dose not exists as next will be created/addded
if (!majom.ContainsKey(key))
{
majom[key] = 0;
}
// the value coresponding to the already existing key will be increased
majom[key] += value;
//foreach (var item in majom)
//{
// if (item.Key == row[0])
// {
// duplicate = true;
// i = int.Parse(row[1]);
// item.Value += i; I'm stuck at here. I dont know how am i able to modify the Value
// }
//}
//if (!duplicate)
//{
// i = int.Parse(row[1]);
// majom.Add(row[0], i);
//}
}
foreach (var item in majom)
{
Console.WriteLine(item.Key + ": " + item.Value);
}
}
}https://stackoverflow.com/questions/66932130
复制相似问题