How to take the most frequent number added to the array c# - c#

my code is a math game with rand numbers and operations at the end i ask the user if they want to show the operation with the most wrong/right answers i made each time the user answers right/wrong it will add the operation to a WrongOperationArray/RightOperationArray but how do i show the most frequent operation in each array
string[] operators = new string[4]{ "+", "-", "*", "/" };
}
// LOOP THAT WILL SHOW THE QUESTIONS AND ADD THE RIGHT ANSWERS AND WRONG TO A LIST .
string[] rightoperationlist = new string[numofquestions];
string[] wrongoperationlist = new string[numofquestions];
while (numofquestionsleft > 0 && m <=numofquestions+1)
{
string op = operators[randomgen.Next(operators.Length)];
switch (op)
{
case "+":
answer = num01 + num02;
break;
case "-":
answer = num01 - num02;
break;
case "*":
answer = num01 * num02;
break;
case "/":
answer = Math.Round((double)num01 / (double)num02, 2);
break;
}
sss = Convert.ToString(answer);
//THE QUESTION
question = string.Format("{0} {1} {2}", num01, op, num02);
Console.WriteLine("--------------------------------------------------------");
Console.WriteLine("What is = " + question + " Or type QUIT to ignore ");
Console.WriteLine("--------------------------------------------------------");
// IF USER TYPE QUIT THAT WILL SKIP THE QUESTION AND ADD IT TO WRONG ANSWERS LIST
if (useranswer == quit)
{
numofquestionsleft--;
;
continue;
}
if (useranswer == sss)
//IF USER ANSWER IS CORRECT THE NUMBER OF CORRECT ANSWERS WILL +1 && add the operation to the array
{
numofcorrect++;
rightoperationlist[m] = op;
}
else
//IF USER ANSWER IS WRONG THE NUMBER OF WRONG ANSWERS WILL +1 && add the operation to the array
{
numoffalse++;
wrongoperationlist[m] = op;
}
numofquestionsleft--;
//LOOP
m++;
}
while (1 < 2)
{
Console.WriteLine(#"TO GET THE NUMBER OF THE RIGHT ANSWERS PRESS 1
TO GET THE NUMBER OF THE WRONG ANSWERS PRESS 2
TO GET THE OPERATION WITH THE MAX NUMBERS OF RIGHT ANSWERS PRESS 3
TO GET THE OPERATION WITH THE MAX NUMBERS OF FALSE ANSWERS PRESS 4
TO VIEW ALL THE QUESTIONS AND YOUR ANSWERS AND CORRECT ANSWERS TYPE 5
TO EXIT TYPE EXIT
");
sb = Console.ReadLine();
b = Int32.Parse(sb);
switch (b)
{
case 1:
Console.WriteLine("-----------------------------------------------");
Console.WriteLine("You have = " + numofcorrect + " Right answers");
Console.WriteLine("-----------------------------------------------");
break;
case 2:
Console.WriteLine("-----------------------------------------------");
Console.WriteLine("You have = " + numoffalse + " Wrong answers");
Console.WriteLine("-----------------------------------------------");
break;
case 3:
for (int l=0; l< numofcorrect;l++ )
{
Console.WriteLine("RIGHT ANSWER OPERATION = " + rightoperationlist[l]);
}
break;
case 4:
for (int k = 0; k < numoffalse; k++)
{
Console.WriteLine("WRONG ANSWER OPERATIONS = "+ wrongoperationlist[k]);
}
break;
case 5:
Console.WriteLine("QUESTIONS ANSWERS RIGHTANSWERS");
Console.WriteLine("------------------------------------------------------------------------");
for (int z = 0; z < numofquestions; z++)
{
Console.WriteLine(questionlist[z]+" "+useranswerlist[z]+" "+rightanswerslist[z]);
}
Console.WriteLine("------------------------------------------------------------------------");
break;
default:
break;
}
}
Console.ReadLine();

You can use linq, there is example:
var result = (from operation in rightoperationlist
group operation by operation into og
orderby og.Count() descending
select og.Key).FirstOrDefault();

Based on my test, you can select the operation and the count of the array first.
Then, you can select the max count of the list.
Finally, you can get the correct result.
static void Main(string[] args)
{
string[] operators = new string[4] { "+", "-", "*", "/" };
int numofquestions = 6;
int numofquestionsleft = 2;
Random random = new Random();
double answer = 0;
Console.WriteLine("Please enter two numbers");
double num01 = Convert.ToInt32(Console.ReadLine());
double num02 = Convert.ToInt32(Console.ReadLine());
int m = 0 ;
string[] rightoperationlist = new string[numofquestions];
string[] wrongoperationlist = new string[numofquestions];
int numofcorrect = 0;
int numoffalse = 0;
while (numofquestionsleft > 0 && m <= numofquestions-1 )
{
string op = operators[random.Next(operators.Length)];
switch (op)
{
case "+":
answer = num01 + num02;
break;
case "-":
answer = num01 - num02;
break;
case "*":
answer = num01 * num02;
break;
case "/":
answer = Math.Round((double)num01 / (double)num02, 2);
break;
}
string sss = Convert.ToString(answer);
//THE QUESTION
string question = string.Format("{0} {1} {2}", num01, op, num02);
Console.WriteLine("--------------------------------------------------------");
Console.WriteLine("What is = " + question + " Or type QUIT to ignore ");
Console.WriteLine("--------------------------------------------------------");
string useranswer = Console.ReadLine();
// IF USER TYPE QUIT THAT WILL SKIP THE QUESTION AND ADD IT TO WRONG ANSWERS LIST
if (useranswer == sss)
//IF USER ANSWER IS CORRECT THE NUMBER OF CORRECT ANSWERS WILL +1 && add the operation to the array
{
Console.WriteLine("correct answer!");
numofcorrect++;
rightoperationlist[m] = op;
}
else
//IF USER ANSWER IS WRONG THE NUMBER OF WRONG ANSWERS WILL +1 && add the operation to the array
{
Console.WriteLine("Incorrect Answer");
numoffalse++;
wrongoperationlist[m] = op;
}
//numofquestionsleft--;
//LOOP
m++;
}
var correctresult= rightoperationlist.ToList().GroupBy(x => x)
.Where(g => g.Count() >=1)
.Select(y => new { Element = y.Key, Counter = y.Count() })
.ToList();
Console.WriteLine("The most frequent operation and the count in the correct array");
int max1 = correctresult.Max(r => r.Counter);
foreach (var item in correctresult)
{
if(item.Element!=null&&item.Counter==max1)
{
Console.WriteLine("The most operation is {0} and the count is {1}", item.Element, item.Counter);
}
}
var wrongresult = wrongoperationlist.ToList().GroupBy(x => x)
.Where(g => g.Count()>=1)
.Select(y => new { Element = y.Key, Counter = y.Count() })
.ToList();
Console.WriteLine("The most frequent operation and the count in the wrong array");
int max2 = wrongresult.Max(r => r.Counter);
foreach (var item in wrongresult)
{
if(item.Element!=null&&item.Counter==max2)
{
Console.WriteLine("The most operation is {0} and the count is {1}", item.Element, item.Counter);
}
}
Console.WriteLine("success");
Console.ReadLine();
}
Tested result:

Related

how many time a char have been repeted in a random string

I have this code which is a simple game you pick how many questions and how many characters you want and the program generate a random string of characters and numbers but how do I pick one random character every question and ask the user how many time this char have been repeated for example
how many time char A have been repeated in this string: iasfhAjfalkjA
answer = 2 times
I don't know If I should put the whole code but I think it helps here is my code
{
class MainClass
{
public static void Main(string[] args)
{
Random randomgen = new Random();
int a; string Sa; int b; string sb;
int maxanswer = 0;
int m = 0;
string question;
string sss;
string quit = "QUIT";
string useranswer;
string answer ;
int numofquestions;
int numofquestionsleft;
int numofcorrect = 0;
int numoffalse = 0;
//ASKING THE USER FOR THE MAX NUMBER OF QUESTIONS WANT TO BE ASKED
Console.Write("Max Question : ");
numofquestions = Convert.ToInt32(Console.ReadLine());
numofquestionsleft = numofquestions;
//ASKING THE USER TO PUT A NUMBER BETWEEN 3 AND 100 THAT WILL HELP GENERATE A RANDOM string
Console.WriteLine("enter a value between 3 and 100");
Sa = Console.ReadLine(); a = Int32.Parse(Sa);
//here is the random generating part
String sarffsa = "A1a2B3b4C5c6D7d8E9eFfGgHhIiKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
while (numofquestionsleft > 0 && m <= numofquestions + 1)
{
int length = a;
String random = "";
for (int i = 0; i < length; i++)
{
int alphapet = randomgen.Next(42);
random = random + sarffsa.ElementAt(alphapet);
}
Console.WriteLine("How many time the symbol has been repeted in the follwing characters: {0}", random);
answer = Console.ReadLine();
// adding the question and the user answer and the right answer to an array
questionlist[m] = random;
useranswer = Convert.ToString(Console.ReadLine());
useranswerlist[m] = answer;
rightanswerslist[m] = answer;
Console.WriteLine("--------------------------------------------------------");
// IF USER TYPE QUIT THAT WILL SKIP THE QUESTION AND ADD IT TO WRONG ANSWERS LIST
if (answer== quit)
{
numofquestionsleft--;
;
continue;
}
numofquestionsleft--;
//LOOP
m++;
}
while (1 < 2)
{
Console.WriteLine(#"TO GET THE NUMBER OF THE RIGHT ANSWERS PRESS 1
TO GET THE NUMBER OF THE WRONG ANSWERS PRESS 2
TO GET THE OPERATION WITH THE MAX NUMBERS OF RIGHT ANSWERS PRESS 3
TO GET THE OPERATION WITH THE MAX NUMBERS OF FALSE ANSWERS PRESS 4
TO VIEW ALL THE QUESTIONS AND YOUR ANSWERS AND CORRECT ANSWERS TYPE 5
TO EXIT TYPE EXIT
");
sb = Console.ReadLine();
b = Int32.Parse(sb);
switch (b)
{
// the number of right answers
case 1:
Console.WriteLine("-----------------------------------------------");
Console.WriteLine("You have = " + numofcorrect + " Right answers");
Console.WriteLine("-----------------------------------------------");
break;
case 2:
// the number of wrong answers
Console.WriteLine("-----------------------------------------------");
Console.WriteLine("You have = " + numoffalse + " Wrong answers");
Console.WriteLine("-----------------------------------------------");
break;
// Making the rightoperationlist into a group in order and count to show the most frequent array used
case 3:
var result = (from operation in rightoperationlist
group operation by operation into og
orderby og.Count() descending
select og.Key).FirstOrDefault();
Console.WriteLine("RIGHT ANSWER OPERATION = " + result);
break;
case 4:
// Making the Wrongoperationlist into a group in order and count to show the most frequent array used
var result02 = (from operation in wrongoperationlist
group operation by operation into og
orderby og.Count() descending
select og.Key).FirstOrDefault();
Console.WriteLine("WRONG ANSWER OPERATIONS = " + result02);
break;
//showing the questions and user answer and the right answer arrays
case 5:
Console.WriteLine("QUESTIONS ANSWERS RIGHTANSWERS");
Console.WriteLine("------------------------------------------------------------------------");
for (int z = 0; z < numofquestions; z++)
{
Console.WriteLine(questionlist[z] + " " + useranswerlist[z] + " " + rightanswerslist[z]);
}
Console.WriteLine("------------------------------------------------------------------------");
break;
default:
break;
}
}
Console.ReadLine();
}
}
}
To pick one random character (as a string) in the generated random string:
var Symbol = random[randomgen.Next(random.Length)].ToString();
To get the actual answer:
var GameAnswer = random.Count(c => c.ToString() == Symbol);
Of course, if the random character is to be stored as a char instead of a string, it becomes even simpler because we can get rid of the two ToString() calls.
It becomes
var Symbol = random[randomgen.Next(random.Length)]; // Here Symbol type is char
To get the actual answer:
var GameAnswer = random.Count(c => c == Symbol);

Adding switch case

I want to add switch case to not allow the user to write string when entering temperature or when there is nothing to delete it says "there is nothing to delete, go back to menu".
List<string> Temp = new List<string>();
while (true)
{
string val;
Console.WriteLine("[L] ägg till temp-mätning: ");
Console.WriteLine("[S] kriv ut alla temperaturer och medeltemperatur");
Console.WriteLine("[T] ag bort temp-mätning");
Console.WriteLine("[A] vsluta");
Console.Write("Selection: ");
val = Console.ReadLine();
if (val == "l" || val == "L")
{
Console.WriteLine("add temperature : ");
Temp.Add(Console.ReadLine());
Console.Clear();
}
else if(val == "s" || val == "S")
{
int index = 1;
Console.Clear();
Console.WriteLine($"Your temperatures are: ");
Temp.ForEach(x => Console.WriteLine($"{index++} - {x}"));
}
else if (val == "t" || val == "T")
{
Console.Write($"Which temp do you want to delete [index from 1 to {Temp.Count}]: ");
int deleteIndex = int.Parse(Console.ReadLine()) - 1;
Temp.RemoveAt(deleteIndex);
}
else
{
Console.WriteLine("incorrect input: ");
Console.Clear();
break;
}
To control use input you can extract methods, e.g.
private static int ReadInteger(string title) {
while (true) {
if (!string.IsNullOrWhiteSpace(title))
Console.WriteLine(title);
if (int.TryParse(Console.ReadLine(), out int result))
return result;
Console.WriteLine("Incorrect syntax, please, try again.");
}
}
then you can put
val = Console
.ReadLine()
.Trim() // Let's be nice and tolerate leading / trailing spaces, e.g. " L "
.ToUpper();
val = val.Substring(0, Math.Max(1, val.Length));
switch (val) {
case "L":
// We read valid integer, turn it to string and out to Temp
Temp.Add(ReadInteger("add temperature : ").ToString());
Console.Clear();
break;
case "T":
int deleteIndex = ReadInteger(
"$"Which temp do you want to delete [index from 1 to {Temp.Count}]: ");
if (deleteIndex >= 0 && deleteIndex < Temp.Count)
Temp.RemoveAt(deleteIndex);
else
Console.WriteLine("Index out of range");
break;
...
}
Please check C# reference websites or books before asking questions.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/
Here is the code you wanted, hope this helps you:
List<string> Temp = new List<string>();
while (true)
{
menu:
string val = string.Empty;
Console.WriteLine("[L] ägg till temp-mätning: ");
Console.WriteLine("[S] kriv ut alla temperaturer och medeltemperatur");
Console.WriteLine("[T] ag bort temp-mätning");
Console.WriteLine("[A] vsluta");
Console.Write("Selection: ");
val = Console.ReadLine();
switch (val.ToLower())
{
case "l":
addTemperature:
Console.WriteLine("add temperature : ");
string temperatureInput = Console.ReadLine();
int temperatureToAddToList;
try
{
temperatureToAddToList = Convert.ToInt32(temperatureInput); //This line trys to convert string variables to integer variables. If string variable includes any character, it will throw an exception.
}
catch (Exception error) //If an exception was thrown, this code block gets activated, which will give out the message you asked for.
{
Console.Clear();
Console.WriteLine("Please enter a number instead of a string!");
goto addTemperature;
}
Temp.Add(temperatureInput.Trim());
Console.Clear();
break;
case "s":
int index = 1;
Console.Clear();
Console.WriteLine($"Your temperatures are: ");
Temp.ForEach(x => Console.WriteLine($"{index++} - {x}"));
break;
case "t":
if (Temp.Count == 0)
{
Console.Clear();
Console.WriteLine("There is nothing to delete, go back to menu.");
goto menu;
}
else
{
Console.Write($"Which temp do you want to delete [index from 1 to {Temp.Count}]: ");
int deleteIndex = int.Parse(Console.ReadLine()) - 1;
Temp.RemoveAt(deleteIndex);
break;
}
default:
Console.WriteLine("incorrect input: ");
Console.Clear();
break;
}
I have revised and updated my code example to better solve your problem.

1. How can I get my random number to be different each time it is printed out? 2. Are there any basic things that I can improve upon? [duplicate]

This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 4 years ago.
I am very new to programming as a whole and C# is my first language. I have been working on this project for the past few weeks or so that gives the user 3 options of whether they want to use a random number generator, calculator or roll a dice.
So far everything is going okay. I have been focusing quite a lot on exception handling and commenting to make sure that everything is as clear as possible. One problem that I have come across and am not surer how to fix is that in my dice rolling procedure it prints out the same random dice number x times rather than printing out different random numbers each time. So if you could help me fix that that would be awesome. Here is just the code for that;
static void rollDice()
{
Boolean rollAgain = false;
while (rollAgain == false)
{
Console.Write("Enter the number of sides on your dice: "); //Need to do exception handling for this
int totalSides = int.Parse(Console.ReadLine());
Console.WriteLine("How many times would you like to roll the {0} sided dice?", totalSides); //Need to do exception handling for this
int numRolls = int.Parse(Console.ReadLine());
for (int i = 0; i < numRolls; i++)
{
Random rnd = new Random();
int diceNumber = rnd.Next(1, totalSides);
Console.Write("\t" + diceNumber);
}
Console.WriteLine("\nIf you like to roll a dice with a different number of sides enter Y\nTo exit the application enter N");
string doRerun = Console.ReadLine();
if (doRerun == "Y" || doRerun == "y")
{
rollAgain = false;
}
else if (doRerun == "N" || doRerun == "n")
{
rollAgain = true;
}
}
}
Also, as I'm a newbie in general, I think some feedback from more experienced users will benefit me as a whole. Is there any mistakes I've made> Any informal rules I have broken? Please let me know I will be very thankful. Here is all of the code;
static void Main(string[] args)
{
Boolean chooseRun = false;
while (chooseRun == false)
{
Console.WriteLine("To use the calculator enter C\nTo use the random number generator enter R\nTo roll a dice enter D");
string chooseProc = Console.ReadLine();
if (chooseProc == "C" || chooseProc == "c")
{
calculator();
chooseRun = true;
}
else if (chooseProc == "R" || chooseProc == "r")
{
numGenerator();
chooseRun = true;
}
else if (chooseProc == "D" || chooseProc == "d")
{
rollDice();
chooseRun = true;
}
else
{
Console.WriteLine("Sorry that was an invalid input. Please try again");
chooseRun = false;
}
}
Console.Write("Goodbye");
Console.ReadKey();
}
/// <summary>
/// Here I have a simple calculator that can do basic functions such as subtraction and then I give them the option to use it again
/// </summary>
static void calculator()
{
int loop = 1;
while (loop == 1)
{
Console.WriteLine("You chose to use the calculator!\nPress the enter key to start"); //Greet the user and give them the option of when they want to start the calculator based upon when they choose to click the enter key
Console.ReadKey(true);
int num1 = 0; //Declaring variables
int num2 = 0;
string operation = "";
int answer;
Boolean gotnum1 = false;
while (gotnum1 == false)
{
Console.Write("Enter the first number in your equation: "); //Then I give them a message to greet them and give them the option of when to start the calculator
try
{
num1 = int.Parse(Console.ReadLine());
gotnum1 = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Boolean gotnum2 = false;
while (gotnum2 == false)
{
Console.Write("Enter the second number in your equation: "); //Then I give them a message to greet them and give them the option of when to start the calculator
try
{
num2 = int.Parse(Console.ReadLine());
gotnum2 = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Boolean gotOpr = false;
while (gotOpr == false)
{
Console.Write("Ok now enter your operation ( x , / , +, -) ");
operation = Console.ReadLine();
switch (operation)
{
case "x":
answer = num1 * num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
case "X":
answer = num1 * num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
case "/":
try
{
answer = num1 / num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
}
catch (DivideByZeroException e)
{
Console.WriteLine("You cannot divide by zero");
}
break;
case "+":
answer = num1 + num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
case "-":
answer = num1 - num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
default:
Console.WriteLine("Sorry that is an invalid input");
gotOpr = false;
break;
}
}
Console.WriteLine("Do you want to use the calculator again? Select;\nIf you would please enter /Y/\nIf not please enter /N/");
string rerun = Console.ReadLine();
if (rerun.ToUpper() == "N")
{
loop = 0;
}
}
}
/// <summary>
/// This procedure generates a random number and gives the user the option as to whether they would like to generate another
/// </summary>
static void numGenerator()
{
Console.WriteLine("You chose to use the random number generator");
Boolean moreNum = false;
while (moreNum == false)
{
Random r = new Random();
int n = r.Next();
Console.WriteLine(n);
Console.WriteLine("If you would like another number enter Y, otherwise please enter N");
string rerun = Console.ReadLine();
if (rerun == "Y" || rerun == "y")
{
moreNum = false;
}
else if (rerun == "N" || rerun =="n")
{
moreNum = true;
}
}
}
/// <summary>
/// In this procedure a virtual dice is rolled of a user inputted number of times, this too gives the user the option to roll the dice again after rolling it x times
/// </summary>
static void rollDice()
{
Boolean rollAgain = false;
while (rollAgain == false)
{
Console.Write("Enter the number of sides on your dice: "); //Need to do exception handling for this
int totalSides = int.Parse(Console.ReadLine());
Console.WriteLine("How many times would you like to roll the {0} sided dice?", totalSides); //Need to do exception handling for this
int numRolls = int.Parse(Console.ReadLine());
for (int i = 0; i < numRolls; i++)
{
Random rnd = new Random();
int diceNumber = rnd.Next(1, totalSides);
Console.Write("\t" + diceNumber);
}
Console.WriteLine("\nIf you like to roll a dice with a different number of sides enter Y\nTo exit the application enter N");
string doRerun = Console.ReadLine();
if (doRerun == "Y" || doRerun == "y")
{
rollAgain = false;
}
else if (doRerun == "N" || doRerun == "n")
{
rollAgain = true;
}
}
}
You should create the Random object only once, typically create is in a static field (if you create it many times, it would generate the same values every time)
static Random rnd = new Random();

c# random operators and math problems, do loop

Hey guys im trying to work on this assignment i have. I am new to programming and this is my third assignment. Any help would be appreciated. Im not sure if im on the right track or not. here is what i have to do:
allow the user to enter a numeric answer to math problem and display their average score. The user will be allowed to answer as many math problems as they choose. After each entry we will display the current average score. The difference between the while loop and the do loop is the while loop tests a condition before running its code block where the do loop will execute its code block and then test a condition. Hence the names of pre-test loop for the while loop and post-test loop for the do loop. Since the do loop is a post-test loop, it will always execute its code block one time at a bare minimum.
these are the steps im trying to follow:
Inside the Main method block of code we are going to create a do loop. The advantage of a do loop is that it will always execute one time. In this application we will use that advantage to repeat several steps. The following steps are what we want to repeat:
Clear the console Display window. (This will keep the display from getting cluttered)
Use random object to get/store two random numbers for a math problem.
Randomly decide which math operator to use (+-*/)and store the symbol.
Display an application header and the math problem formatted.
Get the answer from the user and store it in a variable(i.e.“input”).
Convert variable(input)from a string to a double or integer.
Based on the math symbol calculate the correct answer using random numbers.
If user entry matches correct answer,add question point value to points earned total.
Add the question point value to the points possible total.
Display message with points earned, possible, and the average (earned/possible).
Display a message asking the user if they want to quit or get a new math problem.
Pause display and get the user response of quit or continue.!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MathProblems
{
class Program
{
static void Main(string[] args)
{
string input;
double totalPoints = 0;
double userEarnedPoints = 0;
double average = 0;
int number1 = 0;
int number2 = 0;
int operators = 0;
int answer = 0;
double correctAnswer = 0;
int mathProblem = 0;
do
{
Console.Clear();
Random number = new Random();
number1 = number.Next(1, 31);
number2 = number.Next(1, 31);
operators = number.Next(1, 5); // 1 = add, 2 = minus, 3 = multiply, 4 = divide
Console.WriteLine("\tMath Problems\n");
switch (operators)
{
case 1:
answer = number1 + number2;
break;
case 2:
answer = number1 - number2;
break;
case 3:
answer = number1 * number2;
break;
case 4:
answer = number1 / number2;
break;
default:
break;
}
//if (operators == 1)
//{
// Console.WriteLine("{0} + {1} = ", number1, number2);
//}
//else if (operators == 2)
//{
// Console.WriteLine("{0} - {1} = ", number1, number2);
//}
//else if (operators == 3)
//{
// Console.WriteLine("{0} * {1} = ", number1, number2);
//}
//else if (operators == 4)
//{
// Console.WriteLine("{0} / {1} = ", number1, number2);
//}
//break;
} while (true);
Console.ReadLine();
In order to get user input, you need to do Console.ReadKey() (for a single character) or Console.ReadLine() (for a string of characters terminated by Enter). You can then capture this input in a variable and then do a comparison on it to get the user's answer or to determine if they want to continue or not.
You also will need to validate that the input was an integer. You can use int.TryParse() to do this. It will return true if the string was an integer, and will store the integer in the out parameter.
You can then compare the userAnswer to the actual answer to see if they got it right. It also looks like you need to increment the total problems and the user score (when they get an answer correct)
One way to do this would be:
{
var rnd = new Random();
var quit = false;
var userScore = 0;
var totalProblems = 0;
var percentCorrect = 0d;
while (!quit)
{
Console.Clear();
var number1 = rnd.Next(1, 31);
var number2 = rnd.Next(1, 31);
var operation = rnd.Next(1, 5);
string operatorString;
int answer;
totalProblems++;
Console.WriteLine("\tMath Problem:");
Console.WriteLine("\t-------------");
switch (operation)
{
case 1:
answer = number1 + number2;
operatorString = "+";
break;
case 2:
answer = number1 - number2;
operatorString = "-";
break;
case 3:
answer = number1 * number2;
operatorString = "*";
break;
case 4:
answer = number1 / number2;
operatorString = "/";
break;
default:
answer = 0;
operatorString = "?";
break;
}
Console.WriteLine("\t{0} {1} {2}", number1, operatorString, number2);
Console.Write("\nEnter your answer here (round down if necessary): ");
var input = Console.ReadLine();
int inputAsInt;
while (!int.TryParse(input, out inputAsInt))
{
Console.Write("Answer must be an integer. Try again: ");
input = Console.ReadLine();
}
if (inputAsInt == answer)
{
Console.WriteLine("Correct!");
userScore++;
}
else
{
Console.WriteLine("Sorry, the correct answer was: {0}", answer);
}
percentCorrect = Math.Round((double)userScore / totalProblems * 100, 2);
Console.WriteLine("\nYou have answered {0} of {1} questions correctly, " +
"for a total of {2}%.", userScore, totalProblems, percentCorrect);
Console.Write("\nPress 'q' to quit, or any other key to continue... ");
if (Console.ReadKey().Key == ConsoleKey.Q) quit = true;
}
var letterGrade =
percentCorrect < 60 ? "F"
: percentCorrect < 67 ? "D"
: percentCorrect < 70 ? "D+"
: percentCorrect < 73 ? "C-"
: percentCorrect < 77 ? "C"
: percentCorrect < 80 ? "C+"
: percentCorrect < 83 ? "B-"
: percentCorrect < 87 ? "B"
: percentCorrect < 90 ? "B+"
: percentCorrect < 93 ? "A-"
: "A";
Console.WriteLine("\n\nThank you for playing. You've earned you a letter " +
"grade of: {0}", letterGrade);
Console.Write("\nPress any key to exit...");
Console.ReadKey();
}

IF statement isn't working as intended

I have two modules, with an if statement.
Here are the two code snippets.
int sum;
int input;
singleDigit(ref firstRandom, ref secondRandom);
Console.Write("{0} + {1} = : ", firstRandom, secondRandom);
input = Convert.ToInt16(Console.ReadLine());
sum = firstRandom + secondRandom;
if (firstRandom + secondRandom == sum)
{
checkanswergradeoneaddition();
}
else
{
checkanswergradeoneadditionFalse();
}`
Here is the module the latter is referring too. Please bear in mind, I have only been in my programming course since September 2nd.
static void checkanswergradeoneadditionFalse()
{
Random rnd = new Random();
int responseTwo = rnd.Next(0, 3);
switch (responseTwo)
{
case 1:
Console.WriteLine("Incorrect, mush!");
break;
case 2:
Console.WriteLine("Wrong again, Einstein");
break;
default:
Console.WriteLine("Default");
break;
}
}
It's not working as intended.
look at this:
sum = firstRandom + secondRandom;
if (firstRandom + secondRandom == sum)
{
checkanswergradeoneaddition();
}
It makes no sense. if sum is assigned A+B then A+B will always == sum. The "else" will never run.
maybe it's supposed to be
if(input==sum)
I think I get what you're trying to say. Your firs if statement will always be true, because it does not compare any of the users input.
int sum;
int input;
singleDigit(ref firstRandom, ref secondRandom);
Console.Write("{0} + {1} = : ", firstRandom, secondRandom);
input = Convert.ToInt16(Console.ReadLine());
sum = firstRandom + secondRandom;
if (firstRandom + secondRandom == sum)
{
checkanswergradeoneaddition();
}
else
{
checkanswergradeoneadditionFalse();
}`
Try changing it to:
int sum;
int input;
singleDigit(ref firstRandom, ref secondRandom);
Console.Write("{0} + {1} = : ", firstRandom, secondRandom);
input = Convert.ToInt16(Console.ReadLine());
sum = firstRandom + secondRandom;
// Changed the first 'if' statement to compare the users input with the sum.
if (input == sum)
{
checkanswergradeoneaddition();
}
else
{
checkanswergradeoneadditionFalse();
}`
Take note of the comment above the first if statement.

Categories