我有两个不同的班级
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");
}
}
我不能使用两个return语句。如何使它只是停止,通过只给出一次消息,但它只是循环显示它循环的次数。
答案 0 :(得分: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);
}
答案 1 :(得分: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);
}
}
答案 2 :(得分: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)