2016-02-17 102 views
-7

我運行我的代碼,但是當它進入switch語句時,它不執行它並從程序中退出。 在switch語句中,當用戶按1時,它將進行加法運算,2進行減法運算等等。 我無法理解錯誤。開關語句不起作用。 C#

int c; c = 0; 
int a; 
int b; 

Console.Write Line("Enter First Number"); 
a = Convert.ToInt16(Console.Read Line()); 
Console.Write Line("Enter First Number"); 
b = Convert.ToInt16(Console.Read Line()); 
Program k = new Program(); 
k.display(); 
switch(c) 
{ 
    case 1 : 
    { 
     Console.Write Line("Answer is {0}",k.add(a,b)); 
    } 
     break; 
    case 2: 
    { 
     Console.Write Line("Answer is {0}", k.sub(a,b)); 
    } 
     break; 
    case 3: 
    { 
     Console.Write Line("Answer is {0}", k.prod(a, b)); 
    } 
     break; 
    case 4 : 
    { 
     Console.Write Line("Answer is {0}", k.divide(a, b)); 
    } 
     break; 
    default: 
     { 
      Console.Write Line("Enter Valid value"); 
     } 
     break; 
} 
    Console.Read Key(); 
} 


public void display() 
{ 
    Console.Write Line("Menu"); 
    Console.Write Line("1.Add"); 
    Console.Write Line("2.Subtract"); 
    Console.Write Line("3.Multiply"); 
    Console.Write Line("4.Divide"); 
    Console.Write Line("5.Modulus"); 
} 
public int add(int x, int y) 
{ 
    int sum; 
    sum = x + y; 
    return sum; 
} 

public int sub(int x, int y) 
{ 
    int subtract; 
    subtract = x - y; 
    return subtract; 
} 

public int prod(int x, int y) 
{ 
    int p; 
    p = x * y; 
    return p; 
} 

public int divide(int x, int y) 
{ 
    int div; 
    div = x/y; 
    return div; 
} 
+3

你要問「C」值之外。總是0 –

+3

你已經設置了'c = 0;'但沒有改變它的值。因此,您的開關箱都不會觸發。 – ChrisF

+1

'switch語句不工作'這是c#的一個已知錯誤:)) – Eser

回答

2

看看你的變量c。代碼通過時總是爲零。你需要在某處使用變量c

4

你不是把一個值在C

添加以下代碼做到這一點:

Console.WriteLine("1 = Add, 2 = Subtract, 3 = Multiply, 4 = Divide"); 
c = Convert.ToInt16(Console.ReadLine()); 

而且你break語句必須是你的括號內:

case 1 : 
{ 
    Console.WriteLine("Answer is {0}",k.add(a,b)); 
    break; 
} 

而你的Write LineRead Line聲明需要變成單個詞WriteLineReadLine

這段代碼真的很亂。你是用微軟的Word寫什麼的?

+2

'Write Line' Read Line'? – Eser

+0

我剛剛在@Syed的示例代碼中複製了[不正確的]示例。我接受了編輯。 –

+1

@DerekTomes你有什麼是正確的,但要仔細看看switch語句..它會一直中斷;不管你輸入什麼號碼,因爲休息是在個別案件陳述之外 – MethodMan

0

什麼時候你指望它打第二個case語句時,你的原代碼breakcase

switch(c) 
{ 
    case 1 : 
    { 
     Console.WriteLine("Answer is {0}",k.add(a,b)); 
    } 
     break; 
    case 2: 
    { 
     Console.WriteLine("Answer is {0}", k.sub(a,b)); 
    } 
     break; 
    case 3: 
    { 
     Console.WriteLine("Answer is {0}", k.prod(a, b)); 
    } 
+0

謝謝我的每一個我通過你的幫助解決它。 –