0

我有 2 个不同的课程

class TollGate
{
    public void Check(int []numbers, int Token)
    {
        int i;
        for (i = 0; i < numbers.Length; i++)
        {
            int s = numbers[i];
            if ( Token > s)
            {
                Console.WriteLine("You Got To Wait");
                return;//this works
            }
            else
            {
                 Console.WriteLine("Hold On Printing a Pass\n\"Happy Trip\"");//this doesn't   
                 return;
            } 
        }
    }
}


class Program
{
    public static void Main()
    {
        int[] numbers = new int[5]  {1, 2, 3, 4, 5};
        Random rnd = new Random();
        int r = rnd.Next(numbers.Length);
        int Token = (numbers[r]);
        Tollgate T = New TollGate();  
        T.Check(numbers, Token);
        Console.WriteLine("Cool"); 
        Console.WriteLine("Hot");
        Console.WriteLine("Freezing");
    }
}

我不能使用两个返回语句。如何让它停止,只给出一次消息,但它只是与循环一起显示它与循环一样多次。

4

3 回答 3

3

这可能是你想要的:

public void Check(int[] numbers, int Token) {
   for (int i = 0; i < numbers.Length; i++) {
       if ( Token > numbers[i]) {
          Console.WriteLine("You Got To Wait");
          return;
       }
    }
}

public static void Main() {
    int[] numbers = new int[] {1, 2};
    int[] tokens = new int[] {1,2,3,4,5};
    Random rnd = new Random();
    int r = rnd.Next(tokens.Length);
    int Token = (tokens[r]);
    Tollgate T = new TollGate();  
    T.Check(numbers, Token); 
}
于 2013-09-03T02:23:48.427 回答
1

由于您 for 中的逻辑很难理解,因此我试图猜测您要做什么

class Tollgate
{
    public void Check(int []numbers, int Token)
    {
        int i;

        //change this for to the actual logic that you need
        //for (int numbers[i] = 0; numbers[i] < numbers.Length; numbers[i]++)
        for (i = 0; i < numbers.Length; i++)
        {
            int s = numbers[i];
            if ( Token > s)
            {
                Console.WriteLine("You Got To Wait");
            }
            else
            {
                //handle else logic

                //if need to stop the loop when this condition is met, insert a "break;" (condition is Token <= s)
            }   

        }
    }
}
class That
{
    public static void Main()
    {
         int[] numbers = {1, 2, 3, 4, 5};
         Random rnd ;
         int r ;
         int Token ;
         Tollgate T ;  

         rnd = new Random();
         r = rnd.Next(numbers.Length);
         Token = numbers[r];
         T = new TollGate();  
         T.Check(numbers, Token); 
    }
}
于 2013-09-03T02:32:04.877 回答
0

正如 King King 所提到的,您可以return在循环中添加一条语句以在该点停止函数。如果要退出循环但不退出函数,请添加continue语句而不是return. 这跳出循环,在实际代码中很有用,即使您的示例代码很简单,不需要它。

   bool waiting = false;
   if ( Token > numbers[i]) {
      Console.WriteLine("You Got To Wait");
      waiting = true;
      break;
   }
   ... // add any additional logic here. can check if(waiting)
于 2013-09-03T05:57:50.723 回答