LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C# trouble with "switch" statement (https://www.linuxquestions.org/questions/programming-9/c-trouble-with-switch-statement-4175413985/)

jpee 06-29-2012 05:13 AM

C# trouble with "switch" statement
 
I copied a program example from "Programming in the key of C#" by charles petzold.
using System;
class calculator
{
static void Main()
{
double Num1, Num2, Result = 0;
bool GotOperation;
Console.Write("Enter first number: ");
Num1 = Double.Parse(Console.ReadLine());

Console.Write("Enter second number: ");
Num2 = Double.Parse(Console.ReadLine());

do
{
Console.Write("Enter the operation (+, -, *, /, %): ");
string op = Console.ReadLine().Trim();
Console.WriteLine("op = {0}" ,op);
GotOperation = true;

switch (op)
{
case "+":
Result = Num1 + Num2;
break;

case "-":
Result = Num1 - Num2;
break;

case "*":
Result = Num1 * Num2;
break;

case "/":
Result = Num1 / Num2;
break;

case "%":
Result = Num1 % Num2;
break;

default:
Console.WriteLine("Operation {0} is not valid",op);
GotOperation = false;
break;

}
}
while (GotOperation);
Console.WriteLine("The result is " + Result);
}
}

See the output. The program doesn't go past I entered the operation.Do I forgot something?
Output:
john@john-Aspire-M1300:~/Documenten$ mono calculator.exe
Enter first number: 45
Enter second number: 9
Enter the operation (+, -, *, /, %): *
op = *
Enter the operation (+, -, *, /, %): +
op = +
Enter the operation (+, -, *, /, %):

pan64 06-29-2012 06:27 AM

please use [code][/code] to keep formatting
I think this is what you implemented, just try to follow the logic:
enter num1, enter num2 and start loop. Inside the loop ask operation, calculate result (in case of valid input), and here comes the end of the loop, so this cycle repeated - until you enter an invalid op. In that case it will exit the loop and after the line containing while finally it will print the content of result (that will contain the result of the last valid calculation).


All times are GMT -5. The time now is 09:53 AM.