Im building a console c# flash card game and I want to keep a score going to show at the end of how many where correct. I am thinking on what is the best course of action to do this I was thinking a for loop but it didn't work for me like I thought that it might and then again I am still new to programming so I am sure maybe I am just doing something wrong.
So, I have a double called answer.
and since I only need a single in I used another int that is called correctAnswer.
I was thinking I could use that to add to the for loop but it didn't go as planned
so, I am just asking for what might be the best course of action to add points to a score. I also see another problem I will have by using answer as it will add a point even if they get it wrong but I can fix that once I get this sorted.
double answer = 0;
int correctAnswer = Convert.ToInt32(answer);
for (correctAnswer = 0; correctAnswer <= answer; correctAnswer++) ;
///Setting up the switch statement
///switch (variable)
/// case 1:
/// code;
/// break;
///
switch (opSign)
{
case 1:
Console.WriteLine("What is the answer to " + num1 + (" Times " + num2 + " ?"));
answer = Convert.ToInt32(Console.ReadLine());
if (answer == num1 * num2)
{
speechAnswers();
Console.WriteLine("You entered " + answer + " as the answer to " + num1 + " times " + num2 + "." + " You are correct good job! ");
}
else if (answer != num1 * num2)
Console.WriteLine("You are incorrect please try again");
break;
This your the code after adding a small bit of code. Every time he answers correctly, Answer is incremented by 1. If you want to reset your score, You will need to make a function for that that happens when maybe, score decreases three times in a streak. This is your game.
double answer = 0;
int correctAnswer = Convert.ToInt32(answer);
for (correctAnswer = 0; correctAnswer <= answer; correctAnswer++) ;
///Setting up the switch statement
///switch (variable)
/// case 1:
/// code;
/// break;
///
switch (opSign)
{
case 1:
Console.WriteLine("What is the answer to " + num1 + (" Times " + num2 + " ?"));
answer = Convert.ToInt32(Console.ReadLine());
if (answer == num1 * num2)
{
speechAnswers();
Console.WriteLine("You entered " + answer + " as the answer to " + num1 + " times " + num2 + "." + " You are correct good job! ");
score += 1; // every time the answer is correct, score is incremented by 1.
}
else if (answer != num1 * num2)
Console.WriteLine("You are incorrect please try again");
// what happens on loss
break;
every time you write a code happens when the answer is correct, Add this
score += 1;
Related
This question already has answers here:
Why does Read interfere with ReadLine? [duplicate]
(1 answer)
why getting null value from console in c# for readLine() after using read()
(1 answer)
Flushing System.Console.Read()
(3 answers)
Closed 1 year ago.
So, I am refreshing myself on C#. I decided to write a simple calculator program and was showing my daughter. I added a while loop to my main and added an if statement to break the loop if the user doesn't want to repeat the process...I added some methods for the operators and added some info at the end. After that it stopped repeating and just totally skips getting input from the "x = (char)Console.Read();" line and exits. Helpful advice would be appreciated, I am still a beginner with coding so please don't criticize me, thanks. Full code below:
using System;
namespace TrueCalculator
{
class Program
{
public static int addition(int num1, int num2)
{
int result = num1 + num2;
return result;
}
public static int subtraction(int num1, int num2)
{
int result = num1 - num2;
return result;
}
public static int division(int num1, int num2)
{
int result = num1 / num2;
return result;
}
public static int multiplication(int num1, int num2)
{
int result = num1 * num2;
return result;
}
static void Main(string[] args)
{
char x = 'y';
while (x == 'y' || x == 'Y')
{
Console.WriteLine("\t\t\tTrue Calculator\n\t\t Only uses whole numbers!\n\t\t ***BETA VERSION***");
Console.WriteLine("Enter first number: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter second number: ");
int num2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please type desired operator to perform: +, -, /, *");
char op = (char)Console.Read();
if (op == '+')
{
Console.WriteLine(num1 + " + " + num2 + " = " + addition(num1, num2));
}
else if (op == '-')
{
Console.WriteLine(num1 + " - " + num2 + " = " + subtraction(num1, num2));
}
else if (op == '/')
{
Console.WriteLine(num1 + " / " + num2 + " = " + division(num1, num2));
}
else if (op == '*')
{
Console.WriteLine(num1 + " * " + num2 + " = " + multiplication(num1, num2));
}
Console.WriteLine("Reset, y/n?");
x = Convert.ToChar(Console.Read());
if (x == 'n' || x == 'N')
{
break;
}
}
Console.WriteLine("\n\n\t\t\tThank you for using True Calculator\n\nDeveloped by Duster_2015..." +
"\nAny comments or suggestions send to: " +
"FIXME: Enter your Duster email.");
Console.ReadKey();
}
}
}
(This applies to Windows which uses \r\n for newlines. Other systems use only \n.)
When the program asks you to enter "+, -, /, *" and you type
+enter
three chars are put into the console's buffer:
+\r\n
These chars sit there until you read them (or flush them). When you do
char op = (char)Console.Read();
Only one of those chars is read. The variable op is assigned to '+' and the + is removed from the console's input buffer, but the buffer still has
\r\n
in it - just waiting to be read.
Then when you do
x = Convert.ToChar(Console.Read());
it sees the \r in the buffer and it is read immediately - you don't get a chance to type anything and x is assigned '\r'. When the loop rolls back to the beginning, (x == 'y' || x == 'Y') is false and it ends.
One solution is to not use Console.Read() and use Console.ReadLine() instead. This reads the entire input buffer - up to and including the next \n - but neither the \r nor the \n are included in the result. Then you can use string comparisons:
string op = Console.ReadLine();
if (op == "+")....
If you want to use char instead, you need to check for blank strings:
string op = Console.ReadLine();
if (!String.IsNullOrEmpty(op)) {
if (op[0] == '+') ....
I just need a little bit of help. I'm pretty new to coding and I watched some videos and managed to get this far without following exact words from videos. I'm just trying to Make a Calculator in a console window that when you type "Multiply" Or "Divide" it will jump to that section and then you can multiply or divide there. Then when you finish it will close the console.
I thought it worked fine at first but since Divide is the second function even if you type "Divide" it won't do anything because it still technically you just went over multiply, you will have to type "Divide" again for it to start the function.
Any help would be appreciated.
using System;
namespace SelfTeaching
{
class Program
{
static void Main(string[] args) //Meathod Aka "Main," This will get called when program Starts
{
int num01;
int num02;
Console.WriteLine("Multiply Or Divide");
if (Console.ReadLine() == "Multiply")
{
Console.Write("Type Number 1: ");
num01 = Convert.ToInt32(Console.ReadLine());
Console.Write("Type Number 2: ");
num02 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The Answer Is; " + num01 * num02);
Console.ReadKey();
Environment.Exit(0);
}
else if (Console.ReadLine() == "Divide")
{
Console.Write("Type Number 1: ");
num01 = Convert.ToInt32(Console.ReadLine());
Console.Write("Type Number 2: ");
num02 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(num01 + " Divided by " + num02 + " Equals: " + num01 / num02);
Console.ReadKey();
Environment..Exit(0);
}
}
}
}
To get Multiply Or Divide from single input, you have to take that string from input and then to use if-else block to follow user's choice.
Also you need to use double instead int, if you need precise result with decimal when you use divide.
class Program
{
static void Main(string[] args)
{
double num01;
double num02;
Console.Write("Multiply Or Divide ");
string userInput = Console.ReadLine();
if (userInput.Equals("Multiply", StringComparison.OrdinalIgnoreCase))
{
Console.Write("Type Number 1: ");
num01 = Convert.ToDouble(Console.ReadLine());
Console.Write("Type Number 2: ");
num02 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("The Answer Is; " + num01 * num02);
Console.ReadKey();
Environment.Exit(0);
}
else if (userInput.Equals("Divide", StringComparison.OrdinalIgnoreCase))
{
Console.Write("Type Number 1: ");
num01 = Convert.ToDouble(Console.ReadLine());
Console.Write("Type Number 2: ");
num02 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(num01 + " Divided by " + num02 + " Equals: " + num01 / num02);
Console.ReadKey();
Environment.Exit(0);
}
}
}
Its a good practice to use DRY principle (Don't Repeat YourSelf)
This is example of better code:
class Program
{
static void Main(string[] args)
{
double num01;
double num02;
Console.Write("Multiply Or Divide ");
string userInput = Console.ReadLine();
Console.Write("Type Number 1: ");
num01 = Convert.ToDouble(Console.ReadLine());
Console.Write("Type Number 2: ");
num02 = Convert.ToDouble(Console.ReadLine());
if (userInput == "Multiply")
{
Console.WriteLine("The Answer Is: " + num01 * num02);
}
else if (userInput == "Divide")
{
Console.WriteLine(num01 + " Divided by " + num02 + " Equals: " + num01 / num02);
}
Console.ReadKey();
Environment.Exit(0);
}
}
You could make a function called Divide first off
static int Divide(int num1, int num2)
{
int num3;
num1 / num2 = num3;
return num3;
}
then you can call that function when they want to divide if Readline is a particular value ( e.g Multiply or Divide ). Now, when they access this function, you can make a boolean var also called Divide that is true when a user has divided for instance:
if ( userinput = "divide" )
{
divide:
// enter num1
// enter num2
Divide(num1, num2): // call function
Console.Write(num3); // display num3
bool divide = true;
if ( divide == true; )
{
goto Divide;
}
I know people advise against using gotos but...
anyways, this would also effectively put people in a constant division loop. You should make a switch statement like #vasily.sib said, and probably with a while loop that constantly checks for keys being pressed so people can break out of the goto statement is what I would do. But anyways, its what you asked for :D
Okay so I am new to C# and I just wanted to create a simple calculator with the console. My question is how could I make the user chose different values for num1 and num2 when they chose to divide zero, or divide by zero to prevent the program from crashing due to an undefined result. I figured I could use a while loop to check and see if answer results as an int, and if not repeat the entire program. How could I check answer to verify the result is an int?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
public static void Main(string[] args)
{
int num1;
int num2;
string operand;
float answer;
while ()
{
Console.WriteLine("Please enter the first number.");
num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter which operator you would like to use(+,-,*,/)");
operand = Console.ReadLine();
Console.WriteLine("Please enter the second number.");
num2 = Convert.ToInt32(Console.ReadLine());
switch (operand)
{
case "+":
answer = num1 + num2;
Console.WriteLine(num1 + " + " + num2 + " = " + answer);
Console.ReadKey();
break;
case "-":
answer = num1 - num2;
Console.WriteLine(num1 + " - " + num2 + " = " + answer);
Console.ReadKey();
break;
case "*":
answer = num1 * num2;
Console.WriteLine(num1 + " * " + num2 + " = " + answer);
Console.ReadKey();
break;
case "/":
if (num2 == 0)
{
Console.WriteLine("You cannot devide by zero, please select a different number.");
num2 = Convert.ToInt32(Console.ReadLine());
}
else if (num1 == 0)
{
Console.WriteLine("You cannot devide zero, please select a different number.");
num1 = Convert.ToInt32(Console.ReadLine());
}
else
{
answer = num1 / num2;
Console.WriteLine(num1 + " / " + num2 + " = " + answer);
Console.ReadKey();
}
break;
}
}
}
}
}
you really only need to check the second value (num2). You'd want to evaluate immediately after the read. How you handle it is up to you. You could loop with a while indefinitely, but you'd also want validate (as with any of these inputs), and give the user an option to quit if they can't understand the directions to input.
A possible solution is using while, see below:
case "/":
while (num2 == 0)
{
Console.WriteLine("You cannot devide by zero, please select a different number.");
num2 = Convert.ToInt32(Console.ReadLine());
}
answer = num1 / num2;
Console.WriteLine(num1 + " / " + num2 + " = " + answer);
Console.ReadKey();
break;
However, you should think about change to use int.TryParse method (https://msdn.microsoft.com/en-us/library/system.int32.tryparse%28v=vs.110%29.aspx), as if the user type something that is not a number, Convert.ToInt32 is going to throw a FormatException (https://msdn.microsoft.com/en-us/library/sf1aw27b%28v=vs.110%29.aspx).
I think the cleanset sollution is to extract some methods (select the code and right click with mouse->refactoring->extractMethod).
one of the functions should be "getSecondNumber"
inside that function you start with "enter second number or click "q" to quit.
end you end with if Int.TryParse results with false, or number==0 call your function again (and you'll come to the starting position of "enter second number..."
good luck
I'm still learning the fundamentals of C# and I'm currently busy with some code which has got me stuck in an infinite loop.
do
{
Console.Write("Please enter the Exam mark for student " + (index + 1) + ": ");
Exam[index] = double.Parse(Console.ReadLine());
Console.Write("Please enter the DP for student " + (index + 1) + ": ");
DP[index] = double.Parse(Console.ReadLine());
Final[index] = (DP[index] + Exam[index]) / 2;
index++;
} while (DP[index] != 999);
The code doesn't break when I type 999.
You increase the index with 1 just before the while condition is checked. I guess the value is 0 on that index...
A solution can be to remember the previous value in a variable, or subtract one from the index:
} while (DP[index - 1] != 999);
Another problem might be the use of a double, since it is imprecise, it doesn't always match to 999 if you entered that value. If you can, use int or decimal.
The title basically says it all. The variable "answer" in my code randomly changes value to another random number when it is defined.
The program is supposed to ask ten random maths questions and tell the user if they have got the correct answer or not, however this doesn't seem to be working at all.
Once the variable has changed, the program then also asks about 3 more questions, and tells the user the answer to each is incorrect.
static void Main(string[] args)
{
Random R = new Random();
double solution = 0;
string sign = "";
int score = 0;
for (int i = 0; i < 10; i++)
{
int X = R.Next(1, 5);
int Y = R.Next(1,10);
int Z = R.Next(1,10);
switch (X)
{
case 1:
solution = Y + Z;
sign = "+";
break;
case 2:
solution = Y - Z;
sign = "-";
break;
case 3:
solution = Y / Z;
sign = "/";
break;
case 4:
solution = Y * Z;
sign = "X";
break;
}
Console.WriteLine("What is " + Y + " " + sign + " " + Z + "?");
double answer = Console.Read();
if (answer == solution)
{
Console.WriteLine("Correct");
score = score + 1;
Console.Read();
}
else if (answer != solution)
{
Console.WriteLine("Incorrect. The correct answer is " + solution);
Console.Read();
}
else
{
Console.WriteLine("Error");
Console.Read();
}
}
}
}
}
Your problem is in Console.Read(). This will return the characters number. Starting at 48 (0x30) for character 0. That's why all of your answers are incorrect.
So I suggest you use Console.ReadLine() and then parse the string to answer.
double answer;
if (!double.TryParse(Console.ReadLine(), out answer))
{
Console.WriteLine("Error");
continue;
}
if (answer == solution)
{
Console.WriteLine("Correct");
score = score + 1;
}
else if (answer != solution)
{
Console.WriteLine("Incorrect. The correct answer is " + solution);
}
The problem is that you are using Console.Read() which returns only the next character code. Instead, you should use Console.ReadLine(). Also after you check the answers you use some unnecessary Console.Read()(s). I have removed them and this code is working perfectly fine: -
static void Main(string[] args)
{
Random R = new Random();
double solution = 0;
string sign = "";
int score = 0;
for (int i = 0; i < 10; i++)
{
int X = R.Next(1, 5);
int Y = R.Next(1,10);
int Z = R.Next(1,10);
switch (X)
{
case 1:
solution = Y + Z;
sign = "+";
break;
case 2:
solution = Y - Z;
sign = "-";
break;
case 3:
solution = Y / Z;
sign = "/";
break;
case 4:
solution = Y * Z;
sign = "X";
break;
}
Console.WriteLine("What is " + Y + " " + sign + " " + Z + "?");
double answer = double.Parse(Console.ReadLine());
if (answer == solution)
{
Console.WriteLine("Correct");
score = score + 1;
}
else if (answer != solution)
{
Console.WriteLine("Incorrect. The correct answer is " + solution);
}
}
}
Another thing is that the division questions are actually integer divisions. If you want decimals instead, you should use something like solution = Math.Round((double)((decimal)Y / (decimal)Z), 3); to check a value rounded to 3 decimal places.
I think your problem lies in the fact that Console.Read returns an integer code for the last character pressed (see https://msdn.microsoft.com/en-us/library/system.console.read(v=vs.110).aspx for details).
You need code something like this:
double answer = double.Parse(Console.ReadLine());
This takes the entire input (which might be more than one character) and converts it to a double (Console.ReadLine returns a string) so you are comparing like with like.
Console.Read();
returns an int value(The ASCII code) and you are storing this as answer which is of type double ! Use
Console.ReadLine();
instead ! Also you need to convert your answer to a double value to be able to compare your answer to the solution!