I have been studying C#, and I have made a simple math quiz program.
Is my program reasonable or is there anything I need to improve?
class Program
{
static void Main(string[] args)
{
Console.WriteLine("============== Math Game ===================");
double num1, num2;
double userInput;
int randomIndex;
double sum = 0;
string operation;
// [2]
//int lives = 0;
// Console.Write("How many lives do you want?\t");
// lives = Convert.ToInt32(Console.ReadLine());
// Console.WriteLine("You have {0} Lives", lives);
bool isPlaying = true;
do
{
// 1 generate randon#
Random rnd = new Random();
randomIndex = rnd.Next(1, 4);
num1 = rnd.Next(1, 11);
num2 = rnd.Next(1, 11);
// 2 cal sum && operation && Display
sum = Cal(num1, num2, randomIndex);
operation = Operation(randomIndex);
// DisplayProblem(num1, num2, operation);
// 3 request input
userInput = RequestInput(num1,num2,operation);
// 4 check answer
CheckAnswer(userInput, sum);
} while (isPlaying);
}
private static double Cal(double num1, double num2, int randomIndex)
{
double sum = 0;
switch (randomIndex)
{
case 1:
sum = num1 + num2;
break;
case 2:
sum = num1 - num2;
break;
case 3:
sum = num1 * num2;
break;
case 4:
sum = num1 / num2;
break;
default:
Console.WriteLine("Error");
break;
}
return sum;
}
private static string Operation(int randomIndex)
{
string operation = "";
switch (randomIndex)
{
case 1:
operation = "+";
break;
case 2:
operation = "-";
break;
case 3:
operation = "*";
break;
case 4:
operation = "/";
break;
default:
Console.WriteLine("error");
break;
}
return operation;
}
private static void DisplayProblem(double num1, double num2, string operation)
{
Console.Write($"{num1} {operation} {num2} = ");
}
private static double RequestInput(double num1, double num2, string operation)
{
DisplayProblem(num1, num2, operation);
double userInput;
while (!Double.TryParse(Console.ReadLine(),out userInput))
{
Console.WriteLine("Invalid input. Please type a whole num");
DisplayProblem(num1, num2, operation);
}
return userInput;
}
private static void CheckAnswer(double userInput, double sum)
{
if (userInput == sum)
{
Console.WriteLine("Correct Answer.");
}
else if(userInput != sum)
{
Console.WriteLine("Wrong Answer.");
}
}
}