C#counting中的方法不';不算
我有这个方法:C#counting中的方法不';不算,c#,C#,我有这个方法: public int IndexOf(string text) { for (Node i = Head; i != null; i = i.Next) { int counter = 0; if (text == i.Text) { return counter;
public int IndexOf(string text)
{
for (Node i = Head; i != null; i = i.Next)
{
int counter = 0;
if (text == i.Text)
{
return counter;
}
counter++;
}
return -1;
}
现在我的列表中有4个字符串,索引总是0。我找不出问题出在哪里
谢谢,您正在初始化for循环中的
计数器=0
,在它之外初始化计数器变量
在您的例子中,for循环内部的计数器变量被初始化为0,对于每个迭代,计数器变量变为0,并且在循环结束时递增1
如果在初始化和递增时打印计数器的值
,您将了解需要在代码中进行哪些修改
public int IndexOf(string text)
{
for (Node i = Head; i != null; i = i.Next)
{
int counter = 0;
Console.WriteLine("Value of counter = "+ counter);
if (text == i.Text)
{
return counter;
}
counter++;
Console.WriteLine("Value of counter post increment = "+ counter);
}
return -1;
}
我指出你哪里出了问题。其他答案将显示您需要在代码中进行哪些更改。您正在初始化for循环中的
计数器=0
,在for循环之外初始化计数器变量
public int IndexOf(string text)
{
for (Node i = Head; i != null; i = i.Next)
{
int counter = 0;
Console.WriteLine("Value of counter = "+ counter);
if (text == i.Text)
{
return counter;
}
counter++;
Console.WriteLine("Value of counter post increment = "+ counter);
}
return -1;
}
在您的例子中,for循环内部的计数器变量被初始化为0,对于每个迭代,计数器变量变为0,并且在循环结束时递增1
如果在初始化和递增时打印计数器的值
,您将了解需要在代码中进行哪些修改
public int IndexOf(string text)
{
for (Node i = Head; i != null; i = i.Next)
{
int counter = 0;
Console.WriteLine("Value of counter = "+ counter);
if (text == i.Text)
{
return counter;
}
counter++;
Console.WriteLine("Value of counter post increment = "+ counter);
}
return -1;
}
我指出你哪里出了问题。其他答案将显示您需要在代码中进行哪些更改。您应该初始化
计数器
变量出环
public int IndexOf(string text)
{
for (Node i = Head; i != null; i = i.Next)
{
int counter = 0;
Console.WriteLine("Value of counter = "+ counter);
if (text == i.Text)
{
return counter;
}
counter++;
Console.WriteLine("Value of counter post increment = "+ counter);
}
return -1;
}
public int IndexOf(string text)
{
int counter = -1;
for (Node i = Head; i != null; i = i.Next)
{
counter++;
if (text == i.Text)
{
return counter;
}
}
return -1;
}
您应该初始化
计数器
循环外变量
public int IndexOf(string text)
{
int counter = -1;
for (Node i = Head; i != null; i = i.Next)
{
counter++;
if (text == i.Text)
{
return counter;
}
}
return -1;
}