[英]Use of unassigned local variable
In my code I am getting the following error: 在我的代码中,出现以下错误:
Use of unassigned local variable 'nonrpeatedChar'
使用未分配的局部变量“ nonrpeatedChar”
Why is this error occurring and how do I fix it? 为什么会发生此错误,我该如何解决?
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();
}
}
Given your code path, there's no guarantee that nonrepeatedChar
has been assigned to before passing it to Console.WriteLine
because the only assignment happens inside fo an if
block which may or may not be hit. 给定您的代码路径,不能保证在将
nonrepeatedChar
传递给Console.WriteLine
之前已经将其分配给了它,因为唯一的分配发生在可能被或可能未被命中的if
块内。
An easy fix would be to assign a default value when you declare it: 一个简单的解决方法是在声明默认值时分配它:
char nonrepeatedChar = default(char);
尝试:
char nonrpeatedChar = new Char();
If str
has a len of 0
, the value of nonrpeatedChar
is undefined. 如果
str
的len为0
,则nonrpeatedChar
的值未定义。 Therefore Console.WriteLine(nonrpeatedChar);
因此
Console.WriteLine(nonrpeatedChar);
does not work. 不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.