我在C#中使用字典,希望显示用户输入的键,如果字典中存在该键,则显示该键及其相应值。此外,继续阅读这些行,直到没有更多的输入。
using System;
using System.Collections.Generic;
using System.IO;
class Solution
{
static void Main(String[] args)
{
string number = Console.ReadLine();
int n;
Int32.TryParse(number, out n);
var phoneBook = new Dictionary<string, string>();
for(int i = 0; i < n; i++)
{
string name = Console.ReadLine();
string phoneNumber = Console.ReadLine();
phoneBook.Add(name, phoneNumber);
}
foreach (var pair in phoneBook)
{
string name = pair.Key;
string phoneNumber = pair.Value;
}
string x = Console.ReadLine();
if(!phoneBook.ContainsKey(x))
{
Console.WriteLine("Not Found");
}
else
{
string result = phoneBook[x];
Console.Write(x);
Console.Write("=");
Console.Write(result);
}
}
}
Error message:
Unhandled Exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: key
at System.Collections.Generic.Dictionary2[TKey,TValue].FindEntry (TKey key) <0x7fb28d7c9320 + 0x0023c> in <3833a6edf2074b959d3dab898627f0ac>:0
at System.Collections.Generic.Dictionary2[TKey,TValue].ContainsKey (TKey key) <0x7fb28d7c8cd0 + 0x00009> in <3833a6edf2074b959d3dab898627f0ac>:0
at Solution.Main (System.String[] args) [0x00096] in solution.cs:30
[ERROR] FATAL UNHANDLED EXCEPTION: System.ArgumentNullException: Value cannot be null.
Parameter name: key
at System.Collections.Generic.Dictionary2[TKey,TValue].FindEntry (TKey key) <0x7fb28d7c9320 + 0x0023c> in <3833a6edf2074b959d3dab898627f0ac>:0
at System.Collections.Generic.Dictionary2[TKey,TValue].ContainsKey (TKey key) <0x7fb28d7c8cd0 + 0x00009> in <3833a6edf2074b959d3dab898627f0ac>:0
at Solution.Main (System.String[] args) [0x00096] in solution.cs:30
发布于 2019-01-12 22:44:37
using System;
using System.Collections.Generic;
using System.IO;
class Solution
{
static void Main(String[] args)
{
var phoneBook = new Dictionary<string, string>();
int n = Convert.ToInt32(Console.ReadLine());
for(int i = 0; i < n; i++)
{
string[] record = Console.ReadLine().Split();
string name = record[0];
string phoneNumber = record[1];
phoneBook.Add(name, phoneNumber);
}
string x;
while((x = Console.ReadLine()) != null)
{
if(phoneBook.ContainsKey(x))
{
Console.WriteLine(x + "=" + phoneBook[x]);
}
else
{
Console.WriteLine("Not found");
}
}
}
}
这是对我有效的最终解决方案。更改: 1.增加while
循环条件,避免空搜索字符串。2.删除不需要的foreach
循环。3.在接受字典输入的for
循环中,使用数组在字典的每个记录/条目中存储两个字符串。
发布于 2019-01-11 05:56:39
更改行:
if(!phoneBook.ContainsKey(x))
至:
if(x == null || !phoneBook.ContainsKey(x))
我相信错误指向的是那一行代码。请添加指向出错代码行的注释(以方便我们),并将异常文本重新格式化为代码(去掉反勾号),以便堆栈可读。
发布于 2019-01-11 06:00:09
简而言之,您的其中一个对象是null
。最有可能的一个变量是通过调用Console.ReadLine
设置的。
人们普遍认为Console.ReadLine
不能返回null
。这是假的。如果在控制台输入Control-Z
,则返回null
。
因此,您需要在与Dictionary
交互之前检查null
(例如,调用Add
或ContainsKey
)。或者,从以下位置更改您的ReadLine
调用:
string x = Console.ReadLine();
至:
string x = Console.ReadLine() ?? string.Empty;
为了确保变量不能为null
。
此外,作为优化,可以考虑使用TryGetValue
而不是ContainsKey
,以避免后面的[]
调用。
https://stackoverflow.com/questions/54137356
复制相似问题