10

我正在研究这个代码示例:

class Program
{
    static void Main(string[] args)
    {
        int x = 10;
        int y = 10;

        int generate=0;

        string [,] myArrayTable = new string[x, y];

        Console.WriteLine("Enter a seek number: ");
        string cautat = Console.ReadLine();

        for (int i = 0; i < x; i++)
        {
            for(int j = 0;j < y; j++)
            {
                myArrayTable[i, j] = (generate++).ToString();
            }
        }

        for(int i=0;i<x;i++)
        {
            for(int j=0;j<y;j++)
            {
                if(cautat.Equals(myArrayTable[i,j]))
                {
                    goto Found; 
                }
            }
        }

        goto NotFound;

        Found: 
          Console.WriteLine("Numarul a fost gasit");

        NotFound:
         Console.WriteLine("Numarul nu a fost gasit !");

        Console.ReadKey();
    }
}

我不明白为什么“未找到”语句被调用,并且如果我输入像 10 这样的搜索编号,则在控制台上打印相应的消息,在这种情况下 goto: Found 语句正在执行,所以 goto: NotFound 语句将永远不会被调用,但是它的相应消息仍然打印在控制台上,我不明白为什么在这种情况下程序永远不会跳转到这个“NotFound”标签。

如果你现在帮我解决这个问题,请...

谢谢

4

6 回答 6

10

Eww goto's,我会使用和if/else声明,但如果你需要 goto's:

Found: 
  Console.WriteLine("Numarul a fost gasit");
  goto End;
NotFound:
  Console.WriteLine("Numarul nu a fost gasit !");
End:
Console.ReadKey();
于 2010-08-31T16:50:18.220 回答
8

我会重写这段代码以避免使用 goto:

string message;
if (myArrayTable.Cast<string>().Contains(cautat)) {
    message = "Found";
} else {
    message = "Not found!";
}
Console.WriteLine(message);
于 2010-08-31T16:50:39.437 回答
4

之所以调用它,是因为您在 Found 标签中的代码没有任何东西可以强制它跳过 NotFound 标签中的代码(除非您再次调用 goto,否则执行将通过标签而不是跳过它)。

话虽这么说,不要使用goto我会说这总是一个坏主意,可以重写。

在您的情况下,您可以添加一个简单的布尔标志来摆脱您的 goto:

static void Main(string[] args)
{
    int x = 10, y = 10;
    bool isFound = false;

    // Rest of the body

    for(int i=0;i<x;i++)
    {
        for(int j=0;j<y;j++)
        {
            if(cautat.Equals(myArrayTable[i,j]))
            {
                isFound = true;
                break;
            }
        }

        if(isFound)
            break;
    }

    if(isFound)
        Console.WriteLine("Numarul a fost gasit");
    else
        Console.WriteLine("Numarul nu a fost gasit!");

    Console.ReadKey();
}
于 2010-08-31T16:48:36.863 回答
1

因为您只是跳转到 Found 标签并继续掉到 Not Found 标签。您需要名为 EndFound 的第三个标签,并在找到后转到它。

Found: 
    Console.WriteLine("Numarul a fost gasit");
    goto EndFound;
NotFound:
    Console.WriteLine("Numarul nu a fost gasit !");
EndFound:
于 2010-08-31T16:49:52.483 回答
1

如果您不希望在执行“找到”语句时执行“未找到”语句,请使用另一个 goto 以跳过未找到部分。goto 跳转到一个部分,但这并不意味着如果没有通过 goto 跳转到该部分,则该部分将不会被执行。请记住,代码以自上而下的方式执行,因此除非您以某种方式跳过一段代码,否则它将执行。

例子:

Found:  
    Console.WriteLine("Numarul a fost gasit"); 

goto ReadKey;

NotFound: 
    Console.WriteLine("Numarul nu a fost gasit !"); 

ReadKey:
    Console.ReadKey(); 
于 2010-08-31T16:51:04.100 回答
0

因为在它跳转到 之后Found,执行只是继续到下一行,恰好是“未找到”控制台写入行。您需要添加另一个 goto 来跳过它(或者更好的是,重新设计它以完全避免 goto)

正是这样的问题,应该避免使用goto。

于 2010-08-31T16:51:01.837 回答