2014-01-26 33 views
-7

下面的代碼給我一個錯誤‘無效的表達術語‘其他’’當我嘗試編譯它,我無法弄清楚如何解決它:如果聲明「無效的表達術語‘其他’

public double CalcTicketCost(int section, double quantity) 
{ 
    double amount = 0; 

    if (int.Parse(lstSectionNumber.SelectedItem.Value) < 150) 
    { 
     amount = premiumTicket * quantity; 
     return amount; 
    } 
    { 
     else (int.Parse(lstSectionNumber.SelectedItem.Value) > 150) // This line is where the problem seems to be 

     amount = basicTicket * quantity; 
    } 
    return amount; 
} 
+1

如果您的代碼和問題整齊地格式化,更容易發現類似問題(以及更多)。 –

+0

如果你在C#中工作,爲什麼不使用Visual Studio?這可能對這類錯誤有幫助。 – aloisdg

+1

@RichardEv請指教我如何更好地格式化我的代碼。 aloisdg我使用VS 2012,這就是我發現我的錯誤。 L.B它是我第一週的學習,我將閱讀關於C#的許多知識,並且我已經在看教程。謝謝大家的反饋 – user3236592

回答

5

你有}else之前,語法應該是...

if (condition) 
{ 
    // condition is true 
} 
else 
{ 
    // condition is false 
} 

不過,也有第二個條件你else之後,所以這應該是一個else if

if (condition1) 
{ 
    // condition1 is true 
} 
else if (condition2) 
{ 
    // condition1 is false, condition2 is true 
} 

而且,你的第一個不需要return amount;你可以寫你的方法是這樣的:

public double CalcTicketCost(int section, double quantity) 
{ 
    double amount = 0; 

    if (int.Parse(lstSectionNumber.SelectedItem.Value) < 150) 
    { 
     amount = premiumTicket * quantity; 
    } 
    else if (int.Parse(lstSectionNumber.SelectedItem.Value) > 150) 
    { 
     amount = basicTicket * quantity; 
    } 

    return amount; 
} 

您可以在MSDN找到documentation that explains this in more detail以及更多。

但是,它看起來像您的代碼可能包含一個錯誤。如果lstSectionNumber.SelectedItem.Value等於 150?應該發生什麼?目前您的方法將返回0。這是期望的行爲嗎?

+0

非常感謝,你解釋了一切。我將我的代碼更改爲公共雙CalcTicketCost(int部分,雙數量) {0} {0} {0} double amount = 0; if (int.Parse(lstSectionNumber.SelectedItem.Value)<= 150) { amount = amount =(quantity * premiumTicket)+(quantity * serviceCharge); 退貨金額; } else { amount =(quantity * basicTicket)+(quantity * serviceCharge); } return amount; – user3236592

+0

很抱歉,很難看到代碼,但我將<150改爲<= 150,因爲我需要包含150到高級票價。除此之外,我還刪除了條件,因爲我不需要它 – user3236592

2
if 
{} 
else{} 

if {} 
{ else } }