2011-10-12 46 views
0

我想要choice == 1只能被选中五次,所以我初始化了一个变量firstClass = 0,然后为firstClass < 5设置了一个do-while。我将firstClass++包括在我的do-while中作为柜台。不过,我认为的Firstclass重新初始化每次我调用该方法CheckIn()时间。我怎样才能防止这种情况发生?提前致谢。当我调用方法时,变量重置为零

using System; 

namespace Assignment7 
{ 
    class Plane 
    { 
     public static void Main(string[] args) 
     { 
      Console.WriteLine("Welcome to the Airline Reservation System."); 
      Console.WriteLine("Where would you like to sit?\n"); 
      Console.WriteLine("Enter 1 for First Class."); 
      Console.WriteLine("Enter 2 for Economy."); 
      CheckIn(); 
     } 

     public static void CheckIn() 
     { 
      int choice = Convert.ToInt32(Console.ReadLine()); 
      int firstClass = 0; 
      int economy = 0; 

      if (choice == 1) 
      { 
       do 
       { 
        Console.WriteLine("You have chosen a First Class seat."); 
        firstClass++; 
        CheckIn(); 
       } while (firstClass < 5); 
      } 
      else if (choice == 2) 
      { 
       do 
       { 
        Console.WriteLine("You have chosen an Economy seat."); 
        economy++; 
        CheckIn(); 
       } while (economy < 5); 
      } 
      else 
      { 
       Console.WriteLine("That does not compute."); 
       CheckIn(); 
      } 
     } 
    } 
} 

回答

2

即完全正常。如果您希望变量的方法之外存在,则必须声明它的方法之外,作为一个“场”。只需移动:

int firstClass = 0; 

的方法外,加入static修改(在这种情况下):

static int firstClass = 0; 

还要注意的是,这本身是不是线程安全的;如果线程是一个问题(例如,ASP.NET),然后使用int newValue = Interlocked.Increment(ref firstClass);。我只在一般情况下static数据应该考虑线程提到这一点,因为,但我怀疑它是不是在你的情况(一个控制台EXE)的问题。

1

firstClass变量是方法作用域。每次调用该方法时,都会重新初始化该变量。要让firstClass成为正在进行的计数器,它需要超出课程范围。

0

你需要采取任何退出条件出你的方法,并把它放在外面,或者通过制造新的方法或将它放在一个已经调用它的人。

例如,你可以这样做:

using System; 

namespace Assignment7 
{ 
    class Plane 
    { 
     public static void Main(string[] args) 
     { 
      Console.WriteLine("Welcome to the Airline Reservation System."); 
      Console.WriteLine("Where would you like to sit?\n"); 
      Console.WriteLine("Enter 1 for First Class."); 
      Console.WriteLine("Enter 2 for Economy."); 
      CheckIn(0, 0); 
     } 

     public static void CheckIn(int firstClassSeatsTaken, int economySeatsTaken) 
     { 
      int choice = Convert.ToInt32(Console.ReadLine()); 

      if (choice == 1) 
      { 
       do 
       { 
        Console.WriteLine("You have chosen a First Class seat."); 
        firstClass++; 
        CheckIn(firstClassSeatsTaken, economySeatsTaken); 
       } while (firstClass < 5); 
      } 
      else if (choice == 2) 
      { 
       do 
       { 
        Console.WriteLine("You have chosen an Economy seat."); 
        economy++; 
        CheckIn(firstClassSeatsTaken, economySeatsTaken); 
       } while (economy < 5); 
      } 
      else 
      { 
       Console.WriteLine("That does not compute."); 
       CheckIn(firstClassSeatsTaken, economySeatsTaken); 
      } 
     } 
    } 
} 
相关问题