c# random operators and math problems, do loop - c#

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();
}

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);

How to take the most frequent number added to the array 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:

Random number guessing game not working C# [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to get this random number guessing game working. The program runs, but it doesn't give the "you won" message when you enter the correct number, and the hint feature does not give the feed back it is supposed to. Any help appreciated.
using System;
namespace randomNumberGame
{
class Program
{
static void Main(string[] args)
{
Random r = new Random();
var val = r.Next(1, 100);
var guess = 0;
bool correct = false;
var attemptsLeft = 5;
Console.WriteLine("I'm thinking of a number between 1 and 100.");
while (!correct && attemptsLeft >= 1)
{
Console.Write("You have " + attemptsLeft + " lives left. Please enter your Guess: ");
string input = Console.ReadLine();
var message = "";
var difference = val - guess;
if (!int.TryParse(input, out guess))
{
Console.WriteLine("That's not a number.");
continue;
}
if (difference == 0)
{
Console.WriteLine("You have won");
correct = true;
}
else
{
if (Math.Abs(difference) >= 50)
{
message = Math.Sign(difference) == -1 ? "Very High" : "Very Low";
}
else if (Math.Abs(difference) < 50 && Math.Abs(difference) >= 20)
{
message = Math.Sign(difference) == -1 ? "High" : "Low";
}
else if (Math.Abs(difference) < 20 && Math.Abs(difference) >= 10)
{
message = Math.Sign(difference) == -1 ? "Moderatley High" : "Moderately Low";
}
else if (Math.Abs(difference) < 10)
{
message = Math.Sign(difference) == -1 ? "Somewhat High" : "Somewhat Low";
}
else Console.WriteLine("???");
}
attemptsLeft--;
}
}
}
}
"it doesn't give the you won message when you enter the correct number"
Actually, it does! But then the program exits so quickly that you never see it. To solve this, add a line that waits for the user to press a key at the end of your Main method, so you can see the final result:
// Add this as the last line of the main method:
Console.ReadKey();
"the hint feature does not give the feed back it is supposed too"
This is because you never output the hint message! At the end of your while loop, add a line to do so:
// Add this as the last line of the while loop:
Console.WriteLine(message);
These things can be found easily if you simply set a breakpoint in your code (in Vistal Studio, click the left margin next to one of the lines and a red dot will appear (or press F9)). Then you can step through the code using F10 and you can watch the values of local variables change and see what is happening step-by-step.
Another way to help avoid problems (and to narrow down where they occur) is to take out chunks of code that does something specific and put it in a method. This will make it easier to debug in the long run.
For example, we can write methods that take in a string to display to the user as a prompt for input, and return a strongly-typed value based on their entry. We can also have these methods take in an optional validation method that can be used to validate that the input they entered falls within a valid range (like a number from 1 to 100, or a name that's not longer than 25 characters):
public static string GetStringFromUser(string prompt,
Func<string, bool> validator = null)
{
string result;
var cursorTop = Console.CursorTop;
do
{
ClearSpecificLineAndWrite(cursorTop, prompt);
result = Console.ReadLine();
} while (!(validator?.Invoke(result) ?? true));
return result;
}
public static int GetIntFromUser(string prompt,
Func<int, bool> validator = null)
{
int result;
var cursorTop = Console.CursorTop;
do
{
ClearSpecificLineAndWrite(cursorTop, prompt);
} while (!int.TryParse(Console.ReadLine(), out result) ||
!(validator?.Invoke(result) ?? true));
return result;
}
private static void ClearSpecificLineAndWrite(int cursorTop,
string message)
{
Console.SetCursorPosition(0, cursorTop);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, cursorTop);
Console.Write(message);
}
We can also write a helper method to get our "difference string", which could take in the guess, the number, and the min and max values, then calculate a percentage of how close they were and then return the appropriate string:
public static string GetDifferenceString(int guess, int number,
int minVal, int maxVal)
{
var percentAway =
Math.Abs(guess - number) / (double)(maxVal - minVal) * 100;
var direction = guess - number > 0 ? "High" : "Low";
if (percentAway < 10) return $"Very close, but {direction}";
if (percentAway < 20) return $"Just a little {direction}";
if (percentAway < 30) return $"Somewhat {direction}";
if (percentAway < 40) return $"Moderately {direction}";
if (percentAway < 50) return $"{direction}";
return $"Very {direction}";
}
This simplifies our main code by removing the loops and checking results from there, and lets us focus on our main tasks:
static void Main(string[] args)
{
var randomNumber = new Random().Next(1, 101);
var maxAttempts = 5;
var guess = 0;
Console.WriteLine("I'm thinking of a number between 1 and 100.");
for (int attempt = 0; attempt < maxAttempts; attempt++)
{
Console.WriteLine($"You have {maxAttempts - attempt} " +
$"out of {maxAttempts} attempts remaining.");
guess = GetIntFromUser("Please enter your guess (1 - 100): ",
i => i > 0 && i < 101);
if (guess == randomNumber)
{
Console.WriteLine($"You have won in {attempt + 1} tries!");
break;
}
Console.WriteLine(GetDifferenceString(guess, randomNumber, 1, 100));
}
if (guess != randomNumber)
{
Console.WriteLine("Sorry, you lose! The number was: " +
$"{randomNumber}");
}
GetKeyFromUser("\nDone! Press any key to exit...");
}

How to press enter for a menu without the enter being used for the next operation

So, I am learning C#, and to practice, I have been trying to make a math solver, so the way I did it, is 1- I present the math question, 2- I receive user-input of the solution, 3- I compare the user's answer to my answer using an if statement, now, I am trying to add a console menu to add different divisions (multiplication/division/sub./add.), i have successfully added the menu, however I am not able to move onto inputting the numbers, the error I get is http://prntscr.com/ohru2i, how can I fix it?
I have tried putting Console.clear(), I have also tried to use break;, but none of them worked
using Figgle;
using System;
using System.Threading;
public class MainClass
{
public static void Main()
{
Console.Title = $"The Math Solver | Correct = 0 | Wrong = 0";
char choice;
for (; ; )
{
do
{
Console.WriteLine("Choose Method:");
Console.WriteLine(" 1. Multiplication");
Console.WriteLine(" 2. Division");
Console.WriteLine(" 3. Addition");
Console.WriteLine(" 4. Subtraction");
Console.WriteLine(" 5. Find the Remainder");
Console.WriteLine("Press Q to Exit ");
do
{
choice = (char)Console.Read();
} while (choice == '\n' | choice == '\r');
} while (choice < '1' | choice > '5' & choice != 'q');
if (choice == 'q') break;
Console.WriteLine("\n");
Console.Clear();
switch (choice)
{
case '1':
{
Console.WriteLine(
FiggleFonts.Standard.Render("Multiplication"));
int milliseconds2 = 2000;
Thread.Sleep(milliseconds2);
int correctAnswers = 0;
int WrongAnswers = 0;
int Number1;
int Number2;
int myInt2;
while (true)
{
Console.WriteLine("Write the first number to multiply");
Number1 = int.Parse(Console.ReadLine());
Console.WriteLine("Write the second number to multiply");
Number2 = int.Parse(Console.ReadLine());
Console.WriteLine($"Write the answer of {Number1} * {Number2}");
myInt2 = int.Parse(Console.ReadLine());
if (myInt2 == Number1 * Number2)
{
Console.WriteLine(
FiggleFonts.Standard.Render("Correct!"));
correctAnswers++;
Console.Title = $"The Math Solver | Correct = {correctAnswers} | Wrong = {WrongAnswers}";
}
else
{
Console.WriteLine(
FiggleFonts.Standard.Render("Wrong"));
WrongAnswers++;
Console.Title = $"The Math Solver | Correct = {correctAnswers} | Wrong = {WrongAnswers}";
}
int milliseconds3 = 2000;
Thread.Sleep(milliseconds3);
Console.Clear();
}
}
}
}
}
The error message I get is http://prntscr.com/ohru2i
You're getting the error when converting a number to a string because console.Read() consumes the first character from the standard input, but leaves the line break from the user hitting enter. Therefore, the next time you go to read a line from the console, you just get a blank line, which is not a valid string for number conversion.
Solution is to use Console.ReadLine() and either look at the first character by indexing the string, or replace choice character constants with string constants.

C# How do I error check the input ensuring only integers between 1-100 are accepted

I'm creating a program for a college assignment and the task is to create a program that basically creates random times table questions. I have done that, but need to error check the input to only accept integer inputs between 1-100. I can not find anything online only for like java or for text box using OOP.
Here is my code:
static void help()
{
Console.WriteLine("This program is to help children learn how to multiply");
Console.WriteLine("The program will create times table questions from 1-10");
Console.WriteLine("The user will be given 10 random questions to complete");
Console.WriteLine("The user will get a score out of 10 at the end");
Console.WriteLine("If the user gets the answer wrong, the correct answer will be displayed");
Console.WriteLine("");
Console.ReadLine();
Console.Clear();
}
static void Main(string[] args)
{
int Random1 = 0;
int Random2 = 0;
int Answer;
int Count = 0;
int Score = 0;
int input = 0;
String choice;
Console.WriteLine("To begin the Maths test please hit any key");
Console.WriteLine("If you need any help, just, type help");
choice = Console.ReadLine();
if (choice == "help")
{
help();
}
while (Count != 10)
{
Random numbers = new Random();
Random1 = numbers.Next(0, 11);
Count = Count + 1;
Random numbers2 = new Random();
Random2 = numbers.Next(0, 11);
Console.WriteLine(Random1 + "x" + Random2 + "=");
input = int.Parse(Console.ReadLine());
Answer = Random1 * Random2;
if (Answer == input)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Correct");
Score = Score + 1;
Console.ResetColor();
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Thats the wrong answer, the correct is " + Answer);
Console.ResetColor();
}
}
if (Score > 5)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Good job you got more than 5 answers correct! With a score of " + Score + " out of 10");
Console.ResetColor();
Console.ReadLine();
}
else if (Score < 5)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("");
Console.WriteLine("Try again you got less than 5 correct! With a score of " + Score + " out of 10");
Console.ResetColor();
Console.ReadLine();
}
}
}
}
Firstly, I suggest you to use TryParse instead of Parse to prevent unexpected errors because of invalid inputs. So, try something like that;
Random numbers = new Random();
Random1 = numbers.Next(0, 11);
Count = Count + 1;
Random numbers2 = new Random();
Random2 = numbers.Next(0, 11);
Console.WriteLine(Random1 + "x" + Random2 + "=");
//Modified
int input = 0;
while (true)
{
if (!int.TryParse(Console.ReadLine(), out input))
{
Console.WriteLine("Invalid Input. Please enter a valid integer.");
}
else
{
if (input >= 1 && input <= 100)
{
break;
}
Console.WriteLine("Invalid Input. Please enter a integer between 1-100.");
}
}
//Modified
I'd simply use a loop that will keep asking for input until it
matches your requirement:
int MinVal = 1; // No magic numbers! You may consider placing them in a config
int MaxVal = 100; // or as static readonly class members (a bit like "const").
int input = -1;
for(;;) // "empty" for-loop = infinite loop. No problem, we break on condition inside.
{
// attempt getting input from user
bool parseOK = int.TryParse(Console.ReadLine(), out input);
// Exit loop if input is valid.
if( parseOK && input >= MinVal && input <= MaxVal ) break;
Console.WriteLine( "Errormessage telling user what you expect" );
}
You may also consider granting only N trys to get the input right.
A few hints:
do not use "magic numbers". Define constants or put numbers into Properties/Settings. Name them self-explanatory and document why you chose the value they happen to have.
The errormessage should tell the user what an expected valid input is (as opposed to what they typed in) not just that their input was invalid.
Whats about this?
input = int.Parse(Console.ReadLine());
if(input > 1 && input < 100){
// valid
}else{
// invalid
}

Categories