2012-09-21 71 views
5

這裏全部披露,我是一名學生做家庭作業。我有2個可以選擇項目的列表框。他們所說的內容不需要提取。我編寫了代碼,除了在代碼結尾的3個變量中出現「使用未分配變量」的錯誤外,其他代碼都可以正常工作。他們是locFees,天和註冊。任何人都可以告訴我我做錯了什麼導致變量沒有價值?列表框未分配變量

private void btnCalc_Click(object sender, EventArgs e) 
    { 
     double registration, lodging, total, days, locFees; 
     int workshopIndex, locationIndex; 
     if (lbWorkshop.SelectedIndex != -1) 
     { 
      workshopIndex = lbWorkshop.SelectedIndex; 
      switch (workshopIndex) 
      { 
       case 0: 
        days = 3; 
        registration = 1000; 
        break; 
       case 1: 
        days = 3; 
        registration = 800; 
        break; 
       case 2: 
        days = 3; 
        registration = 1500; 
        break; 
       case 3: 
        days = 5; 
        registration = 1300; 
        break; 
       case 4: 
        days = 1; 
        registration = 500; 
        break; 
      } 
     } 
     else 
     { 
      MessageBox.Show("You didn't select a workshop."); 
     } 
     if (lbLocation.SelectedIndex != -1) 
     { 
      locationIndex = lbLocation.SelectedIndex; 
      switch (locationIndex) 
      { 
       case 0: 
        locFees = 150; 
        break; 
       case 1: 
        locFees = 225; 
        break; 
       case 2: 
        locFees = 175; 
        break; 
       case 3: 
        locFees = 300; 
        break; 
       case 4: 
        locFees = 175; 
        break; 
       case 5: 
        locFees = 150; 
        break; 
      } 
     } 
     else 
     { 
      MessageBox.Show("You didn't select a city."); 
     } 
     lodging = locFees * days; 
     total = registration + lodging; 
    } 

回答

5

誰能告訴我什麼,我做錯了,導致該變量沒有價值?

當然 - 你忽略了workshopIndex不爲0,1,2,3或4

如果您認爲不應該發生的可能性,只需添加:

default: 
    throw new InvalidOperationException("Invalid selected index " + workshopIndex); 

或者,如果你只是想用一些默認值,這樣做:

default: 
    days = 1; 
    registration = 100; 
    break; 

那是第一您可以用daysregistration未分配的方式結束。

接下來,有一個事實,即只有進入開關塊,如果lbWorkshop.SelectedIndex != -1。你else塊就是:

else 
{ 
    MessageBox.Show("You didn't select a workshop."); 
} 

...讓else塊之後,你會繼續。你可能想:

else 
{ 
    MessageBox.Show("You didn't select a workshop."); 
    return; 
} 

你則得到了同樣的問題爲locFees,無論在switch語句和else塊的條款。

有一件事需要學習:感謝編譯器爲你發現了這些。它阻止了你運行肯定有錯誤的代碼。這總是一件好事。