在我的代码中,我收到以下错误:
使用未分配的局部变量“nonrpeatedChar”
为什么会出现此错误以及如何修复它?
static void firstNonRepeated(string str)
{
int i, j, len;
len = str.Length;
int count = 1;
char nonrpeatedChar;
for (i = 0; i < len; i++)
{
for (j = 0; j < len; j++)
{
if (i != j && str[i] == str[j])
{
count = count + 1;
}
}
if (count == 1)
{
nonrpeatedChar = str[i];
break;
}
}
Console.WriteLine(nonrpeatedChar);
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
给定您的代码路径,无法保证nonrepeatedChar在将其传递给之前已对其进行分配Console.WriteLine,因为唯一的分配发生在if可能会或可能不会被命中的块内。
一个简单的解决方法是在声明时分配一个默认值:
char nonrepeatedChar = default(char);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1871 次 |
| 最近记录: |