2011-10-12 49 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); 
      } 
     } 
    } 
} 
相關問題