c# Simple score system - c#

I'm making a simple game. I'm trying to give the player a +1 score when he has a answer correct, but It keeps saying the same score 1. I want to have the score constantly updated when your answer is correct.
So if you have two answers correct, the score should update to 2, but it doesn't and keeps saying 1...
start:
Random numbergenerator = new Random ();
int num1 = numbergenerator.Next(1,11);
int num2 = numbergenerator.Next(1,11);
int score = 0; // THIS IS THE SCORE
Console.WriteLine("Whats " + num1 + " times " + num2 + "?");
var answer = Convert.ToInt32(Console.ReadLine());
if ( answer == num1 * num2) {
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Thats the correct answer!");
Console.ResetColor();
++score; // Gives score
Console.WriteLine("Your score: " + score);
} else {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Bummer, try again!");
Console.ResetColor();
++score; // Gives score
Console.WriteLine("Your score: " + score);
}
goto start;
}
}
}

1) From C# specification (MSDN)
Furthermore, a variable initializer in a local variable declaration corresponds exactly to an assignment statement that is inserted immediately after the declaration.
In other words every time your program goes to start assignment statement will init score with 0
i suggest to move the initialization before start (it will be better to move numbergenerator initialization too. ) :
Random numbergenerator = new Random ();
int score = 0; // THIS IS THE SCORE
start:
int num1 = numbergenerator.Next(1,11);
int num2 = numbergenerator.Next(1,11);
Console.WriteLine("Whats " + num1 + " times " + num2 + "?");
var answer = Convert.ToInt32(Console.ReadLine());
if ( answer == num1 * num2) {
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Thats the correct answer!");
Console.ResetColor();
++score; // Gives score
Console.WriteLine("Your score: " + score);
} else {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Bummer, try again!");
Console.ResetColor();
++score; // Gives score
Console.WriteLine("Your score: " + score);
}
goto start;
2) Don't use goto. Because
it makes the code confusing
reduces readability
this article about GO TO can be interesting for you.
i suggest to replace
start with while (true){
goto start; with }
it should looks something like this:
Random numbergenerator = new Random ();
int score = 0; // THIS IS THE SCORE
while(true)
{
int num1 = numbergenerator.Next(1,11);
int num2 = numbergenerator.Next(1,11);
Console.WriteLine("Whats " + num1 + " times " + num2 + "?");
var answer = Convert.ToInt32(Console.ReadLine());
if ( answer == num1 * num2) {
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Thats the correct answer!");
Console.ResetColor();
++score; // Gives score
Console.WriteLine("Your score: " + score);
} else {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Bummer, try again!");
Console.ResetColor();
++score; // Gives score
Console.WriteLine("Your score: " + score);
}
}
3) Extract method, it is not critical, but i suggest to improve readability by extracting a method. This method will contain loop body. The code should looks something like this:
public void TryToGuessMultiplication_GameStep(int num1, int num2)
{
Console.WriteLine("Whats " + num1 + " times " + num2 + "?");
var answer = Convert.ToInt32(Console.ReadLine());
if ( answer == num1 * num2) {
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Thats the correct answer!");
Console.ResetColor();
++score; // Gives score
Console.WriteLine("Your score: " + score);
} else {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Bummer, try again!");
Console.ResetColor();
++score; // Gives score
Console.WriteLine("Your score: " + score);
}
}
...
Random numbergenerator = new Random ();
int score = 0; // THIS IS THE SCORE
while(true)
{
int num1 = numbergenerator.Next(1,11);
int num2 = numbergenerator.Next(1,11);
TryToGuessMultiplication_GameStep(int num1, int num2);
}
4) Your code contains bug If you want to increase score only if aswer is correct you should remove ++score from else block.
5) Do not duplicate the code As you can see the last 2 statements in both if block and else block are the same. I suggest to move them out from if else operator:
public void TryToGuessMultiplication_GameStep(int num1, int num2)
{
Console.WriteLine("Whats " + num1 + " times " + num2 + "?");
var answer = Convert.ToInt32(Console.ReadLine());
if ( answer == num1 * num2) {
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Thats the correct answer!");
++score; // Gives score
} else {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Bummer, try again!");
}
Console.ResetColor();
Console.WriteLine("Your score: " + score);
}
It is not all. Now you can see that
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Thats the correct answer!");
is quite similar (but not the same!!!) to
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Bummer, try again!");
and we can't improve our code by moving them out of if else operator. But there is a trick - we can extract method with help of which we will reduce lines of code:
public void PrintUserMessage(ConsoleColor color, string message)
{
Console.ForegroundColor = color;
Console.WriteLine(message);
}
public void TryToGuessMultiplication_GameStep(int num1, int num2)
{
Console.WriteLine("Whats " + num1 + " times " + num2 + "?");
var answer = Convert.ToInt32(Console.ReadLine());
if ( answer == num1 * num2){
PrintUserMessage( ConsoleColor.Green, "Thats the correct answer!");
++score; // Gives score
}else
PrintUserMessage( ConsoleColor.Red,"Bummer, try again!");
Console.ResetColor();
Console.WriteLine("Your score: " + score);
}

Your score is set to 0 after every jump goto start;. Put your score declaration above start: like below:
int score = 0; // THIS IS THE SCORE
start:
...other instructions
Remember, no matter if you are using goto or while, if variable must store state during a loop, declare and initialize it outside that loop.

You're setting score to 0 every time you goto start.
Can you please stop using goto? It hurts my eyes, and I believe many other eyes as well. Use while instead.
If you use while by the way, the problem will disappear as score will not be reset every iteration.

Don't use goto it is bad practice, you should use loop instead.
Your code should look like:
Random numbergenerator = new Random();
int score = 0; // THIS IS THE SCORE
while (true)
{
int num1 = numbergenerator.Next(1, 11);
int num2 = numbergenerator.Next(1, 11);
Console.WriteLine("Whats " + num1 + " times " + num2 + "?");
var answer = Convert.ToInt32(Console.ReadLine());
if (answer == num1 * num2)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Thats the correct answer!");
Console.ResetColor();
++score; // Gives score
Console.WriteLine("Your score: " + score);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Bummer, try again!");
Console.ResetColor();
Console.WriteLine("Your score: " + score);
}
}

Adding to the other answers, since you only want to increase the score when the user gets the correct answer, you should remove the ++score; line from your else statement, as the way you currently have it, the score will increase either way, regardless if the answer is correct or not.

Related

Choosing a Option Based On What you Type

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

Timer with questions in c#

I have a cosole appliction
in this try to set timer that is when question display then timer should be start and when in 10 seconds answer not give then should start next question i want to do this
i am done with
I set 3 conditions first they should type number that how many question want to attemppt then select level then select operator .. so when all question typed i.e.
no of question : 2
level : 1
operator: +
then timer start of 10 seconds and when 10 seconds complete then question is display
where as i want first question display and timer then when question not answered with in 10 seconds then next should start
this is what i do
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int userans;
int computerans;
int numofquestions;
int numofquestionsleft;
int correctanswer = 0;
Console.WriteLine("\t\t OPERATOR OF QUIZ \t\t");
Console.WriteLine("\t\tOperator 1:Addition(+)\t\t");
Console.WriteLine("\t\tOperator 2:Subtarction(-)\t\t");
Console.WriteLine("\t\tLEVELS OF QUIZ\t\t");
Console.WriteLine("\t\tLevel 1 (1-9)\t\t");
Console.WriteLine("\t\tLevel 2 (10-99)\t\t");
Console.WriteLine("\t\t-------------------\t\t");
Console.WriteLine("\t\tYour quiz start now\t\t");
Console.WriteLine("\t\t-------------------\t\t");
Console.Write("How many questions do you want to attempt? ");
numofquestions = Convert.ToInt32(Console.ReadLine());
Console.Write("Which level that you want to play? ");
int level = Convert.ToInt32(Console.ReadLine());
Console.Write("which operator do you want to play?");
string opt = Console.ReadLine();
//for (int a = 10; a >= 0; a--)
//{
// Console.SetCursorPosition(0, 2);
// Console.Write("Generating Preview in {0} ", a); // Override complete previous contents
// System.Threading.Thread.Sleep(1000);
//}
numofquestionsleft = numofquestions;
while (numofquestionsleft > 0)
{
if (level == 1)
{
switch (opt)
{
case "+":
{
int num1 = rnd.Next(1, 10);
int num2 = rnd.Next(1, 10);
Console.Write("What is the sum of " + num1 + " and " + num2 + "? ");
computerans = num1 + num2;
userans = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The correct answer is\n" + computerans);
Console.WriteLine("Your answer is \n" + userans);
if (computerans == userans)
{
Console.WriteLine(" Congratulation your answer is correct!\n");
correctanswer++;
}
else
{
Console.WriteLine(" Sorry your answer is wrong! Try again.\n");
}
numofquestionsleft--;
num1 = rnd.Next(1, 10);
num2 = rnd.Next(1, 10);
Console.WriteLine("Your correct answer are " + correctanswer + " out of attempt" + numofquestions + " question");
break;
}
case "-":
{
int num3 = rnd.Next(1, 10);
int num4 = rnd.Next(1, 10);
Console.Write("What is the subtraction of " + num3 + " and " + num4 + "? ");
computerans = num3 - num4;
userans = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The correct answer is\n" + computerans);
Console.WriteLine("Your answer is \n" + userans);
if (computerans == userans)
{
Console.WriteLine(" Congratulation your answer is correct!\n");
correctanswer++;
}
else
{
Console.WriteLine(" Sorry your answer is wrong! Try again.\n");
}
numofquestionsleft--;
num3 = rnd.Next(1, 10);
num4 = rnd.Next(1, 10);
Console.WriteLine("Your correct answer are " + correctanswer + " out of attempt" + numofquestions + " question");
break;
}
}
}
if (level == 2)
{
switch (opt)
{
case "+":
{
int num1 = rnd.Next(10, 99);
int num2 = rnd.Next(10, 99);
Console.Write("What is the sum of " + num1 + " and " + num2 + "? ");
computerans = num1 + num2;
userans = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The correct answer is\n" + computerans);
Console.WriteLine("Your answer is \n" + userans);
if (computerans == userans)
{
Console.WriteLine(" Congratulation your answer is correct!\n");
correctanswer++;
}
else
{
Console.WriteLine(" Sorry your answer is wrong! Try again.\n");
}
numofquestionsleft--;
num1 = rnd.Next(10, 99);
num2 = rnd.Next(10, 99);
Console.WriteLine("Your correct answer are " + correctanswer + " out of attempt" + numofquestions + " question");
break;
}
case "-":
{
int num3 = rnd.Next(10, 99);
int num4 = rnd.Next(10, 99);
Console.Write("What is the subtraction of " + num3 + " and " + num4 + "? ");
computerans = num3 - num4;
userans = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The correct answer is\n" + computerans);
Console.WriteLine("Your answer is \n" + userans);
if (computerans == userans)
{
Console.WriteLine(" Congratulation your answer is correct!\n");
correctanswer++;
}
else
{
Console.WriteLine(" Sorry your answer is wrong! Try again.\n");
}
numofquestionsleft--;
num3 = rnd.Next(10, 99);
num4 = rnd.Next(10, 99);
Console.WriteLine("Your correct answer are " + correctanswer + " out of attempt" + numofquestions + " question");
break;
}
}
}
//if(numofquestions>)
for (int a = 10; a >= 0; a--)
{
Console.SetCursorPosition(0, 2);
Console.Write("Generating Preview in {0} ", a); // Override complete previous contents
System.Threading.Thread.Sleep(1000);
}
Console.ReadKey();
}
}
}
}
Your code is quite messy. You got everything in a single method. So creating additional method(s), which a timer needs, you cannot access any variable that is important to the timer. You need to start making your own classes. This gives you so much more control over the variables of your program. It is difficult with your code, to put you in the right direction. You need to change so much.
For fun, and some experience as well, I created what you was working on. A calculating game, or test, or w/e you wanna call it. I will share my code with you, in the hope you will learn some things out of it.
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalculatingGame
{
class Program
{
static void Main(string[] args)
{
// Add different difficulty options
Dictionary<string, Difficulty> DifficultyOptions = new Dictionary<string, Difficulty>();
DifficultyOptions.Add("easy", new EasyDifficulty());
DifficultyOptions.Add("medium", new MediumDifficulty());
DifficultyOptions.Add("hard", new HardDifficulty());
// Add different game options
Dictionary<string, GameType> GameOptions = new Dictionary<string, GameType>();
GameOptions.Add("additive", new GameAdditive());
GameOptions.Add("subtractive", new GameSubtractive());
GameOptions.Add("randomize", new GameRandomize());
// Default game settings at start up
string GameDiff = "easy";
string GameMode = "additive";
Console.WriteLine("Welcome to Verkade's Calculating Game.");
Console.WriteLine("By default game difficulty has been set to " + GameDiff);
Console.WriteLine("Type in the following commands to change that:");
// This will take out all possible options out of DifficultOptions variable, and display them
foreach (KeyValuePair<string, Difficulty> kvp in DifficultyOptions)
{
Console.WriteLine("/difficulty " + kvp.Key);
}
Console.WriteLine("");
Console.WriteLine("By default game mode has been set to " + GameMode);
Console.WriteLine("Type in the following commands to change that:");
// This will take out all possible options out of game options and display them
foreach (KeyValuePair<string, GameType> GameTypes in GameOptions)
{
Console.WriteLine("/gamemode " + GameTypes.Key);
}
Console.WriteLine("");
Console.WriteLine("When you're done setting up, type in /start to start the game,");
Console.WriteLine("/stop to stop the game. /exit to stop entirely.");
//This will keep the instance of the game once started
Game CurrentGame = null;
//this will keep the program alive. By typing /exit, it will turn into false, and stops the program.
bool KeepProgramAlive = true;
//This is a loop that keeps on listening to your input
while (KeepProgramAlive)
{
// This will split up the users input, when a space is used.
// This way the first cut will contain /start, /stop, /gamemode, etc. It will be stored as 'UserInput[0]'
// In the second cut, which is 'UserInput[1]', things like 'easy', 'medium', 'hard', 'subtractive', etc will be stored
string[] UserInput = Console.ReadLine().Split(' ');
switch (UserInput[0])
{
case "/exit":
{
KeepProgramAlive = false;
break;
}
case "/start":
{
if (DifficultyOptions.ContainsKey(GameDiff) && GameOptions.ContainsKey(GameMode))
{
Console.WriteLine("Game has been set up. When you're ready, press Enter so you'll get your first question");
CurrentGame = new Game(DifficultyOptions[GameDiff], GameOptions[GameMode]);
}
break;
}
case "/stop":
{
if (CurrentGame != null)
{
CurrentGame.Stop();
CurrentGame = null;
Console.WriteLine("Game has been stopped. You can not change settings and start again if you like.");
}
break;
}
case "/gamemode":
{
// checking the length to see there are 2 values. /gamemode is 1 of them. 'subtractive' is another one.
if (UserInput.Length >= 2)
{
// very important, because i am using a dictionary, i can check whether the gamemode exists or not
if (GameOptions.ContainsKey(UserInput[1]))
{
Console.WriteLine("You have changed gamemode to " + UserInput[1]);
GameMode = UserInput[1];
}
else
{
Console.WriteLine("That gamemode does not exist");
}
}
break;
}
case "/difficulty":
{
if (UserInput.Length >= 2)
{
if (DifficultyOptions.ContainsKey(UserInput[1]))
{
Console.WriteLine("You have changed the difficulty to " + UserInput[1]);
GameDiff = UserInput[1];
}
else
{
Console.WriteLine("That difficulty does not exist");
}
}
break;
}
default:
{
// checking if the game has started, and if so, Handler in the game-class will check your input
if (CurrentGame != null)
{
int NumberGiven;
Int32.TryParse(UserInput[0], out NumberGiven);
CurrentGame.Handler(NumberGiven);
}
break;
}
}
}
}
}
}
Operators.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalculatingGame
{
abstract class GameType
{
public int Answer;
public Random Rnd = new Random();
public abstract string MakeSum(Difficulty Diff);
}
class GameAdditive : GameType
{
public override string MakeSum(Difficulty Diff)
{
int num1 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
int num2 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
Answer = num1 + num2;
return num1 + " + " + num2;
}
}
class GameSubtractive : GameType
{
public override string MakeSum(Difficulty Diff)
{
int num1 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber) + Diff.MaxNumber;
int num2 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
Answer = num1 - num2;
return num1 + " - " + num2;
}
}
class GameRandomize : GameType
{
public override string MakeSum(Difficulty Diff)
{
int mode = Rnd.Next(0, 2);
if (mode == 0)
{
int num1 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
int num2 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
Answer = num1 + num2;
return num1 + " + " + num2;
}
else
{
int num1 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber) + Diff.MaxNumber;
int num2 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
Answer = num1 - num2;
return num1 + " - " + num2;
}
}
}
}
Game.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.Threading.Tasks;
namespace CalculatingGame
{
class Game
{
Difficulty Game_Diff;
GameType Game_Type;
int TicksRemaining = 0;
int TotalAnswers = 0;
int CorrectAnswers = 0;
int WrongAnswers = 0;
Timer TimerCountdown;
public Game(Difficulty GDiff, GameType GType)
{
Game_Diff = GDiff;
Game_Type = GType;
TimerCountdown = new Timer(100);
TimerCountdown.Elapsed += TimerCD;
TimerCountdown.AutoReset = true;
}
public void Handler(int Answer)
{
if (TicksRemaining > 0)
{
if (Answer == Game_Type.Answer)
{
CorrectAnswers++;
Console.WriteLine("Good job. You got the correct answer.");
}
else
{
WrongAnswers++;
Console.WriteLine("Wrong answer. The answer was " + Game_Type.Answer + ".");
}
TotalAnswers++;
Console.WriteLine("Current score: " + CorrectAnswers + " correct answers out of " + TotalAnswers);
TicksRemaining = 0;
Console.WriteLine("Press Enter to get your new sum.");
TimerCountdown.Stop();
}
else
{
string SumText = Game_Type.MakeSum(Game_Diff);
Console.WriteLine("What is the solution to the sum " + SumText);
TicksRemaining = Game_Diff.Time;
TimerCountdown.Start();
}
}
public void TimerCD(Object source, ElapsedEventArgs e)
{
if(TicksRemaining > 0)
{
TicksRemaining--;
if ((TicksRemaining % 10) == 0)
{
Console.Write(Math.Floor((decimal)(TicksRemaining / 10)) + "...");
}
if (TicksRemaining == 0)
{
WrongAnswers++;
Console.WriteLine("\r\nTime is up. The answer was " + Game_Type.Answer);
Console.WriteLine("Press Enter to get your new sum.");
TimerCountdown.Stop();
}
}
}
public void Stop()
{
TimerCountdown.Stop();
}
}
}
Difficulty.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalculatingGame
{
// nice thing about abstract classes and child classes are that you can store a 'EasyDifficulty' object under variable-type 'Difficulty'
// this allows me to create a dictionary, with 'Difficulty' type as value, and yet put all the different child classes in there
// another thing you can do, and you can see it under 'Operators.cs' file, is that you can have a method, with the same name in every
// child class, and yet they perform different things.
abstract class Difficulty
{
public int MinNumber = 1;
public int MaxNumber = 1;
// Time in ticks. 1 tick = 100ms. Reason why I made it so is because maybe you want to give the player 7.5 seconds to do the sum
public int Time = 100;
}
class EasyDifficulty : Difficulty
{
public EasyDifficulty()
{
MinNumber = 1;
MaxNumber = 9;
Time = 100;
}
}
class MediumDifficulty : Difficulty
{
public MediumDifficulty()
{
MinNumber = 1;
MaxNumber = 99;
Time = 75;
}
}
class HardDifficulty : Difficulty
{
public HardDifficulty()
{
MinNumber = 1;
MaxNumber = 999;
Time = 50;
}
}
}
Your delay is only 1 second. Increase the delay to 10 seconds by:
for (int a = 10; a >= 0; a--)
{
Console.SetCursorPosition(0, 2);
Console.Write("Generating Preview in {0} ", a); // Override complete previous contents
System.Threading.Thread.Sleep(10000);
}

Repeat a function if the output is undefined

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

Expected class, delegate, enum, interface or struct

Queston is answered thanks for the help :)
I made a code with multiple methods in a class but when I try to run it it says
Expected class, delegate, enum, interface, or struct
on the two methods that are not the main methods. I read around and found that someone had the same problem and the case was that the methods weren’t in the class. But couldn't figure out how to fix that. Any tips?
PS: I’m pretty new to coding ;)
using System;
namespace Testing
{
public class Calculator
{
public static void Main (string[] args )
{
string answer;
Console.WriteLine ("Would you like to divide or multiply? Type your choice.");
Start:
answer = (Console.ReadLine ());
if (answer == "multiply")
{
MultiplyingMethod;
}
{
else if (answer == "divide")
{
DividingMethod;
}
}
else
{
Console.WriteLine ("Please type multiply or divide.");
goto Start;
}
}
}
public static void DividingMethod ()
{
double num01;
double num02;
Console.Write ("Enter a number to be divided");
num01 = Convert.ToInt32 (Console.ReadLine ());
Console.Write ("Enter a number to divide by");
num02 = Convert.ToInt32 (Console.ReadLine ());
Console.WriteLine (num01 + " divided by " + num02 + " is equal to " + num01 / num02);
Console.WriteLine ("");
Console.ReadKey ();
}
public static void MultiplyingMethod ()
{
double num01;
double num02;
Console.Write ("Enter a number to be multiplied");
num01 = Convert.ToInt32 (Console.ReadLine ());
Console.Write ("Enter a numeber to multiply by");
num02 = Convert.ToInt32 (Console.ReadLine ());
Console.WriteLine (num01 + " multiplied by " + num02 + " equals " + num01 * num02);
Console.WriteLine ("");
Console.ReadKey ();
}
}
}
Working version:
public static void Main(string[] args)
{
string answer;
Console.WriteLine("Would you like to divide or multiply? Type your choice.");
while (true)
{
answer = (Console.ReadLine());
if (answer == "multiply")
{
MultiplyingMethod();
break;
}
else if (answer == "divide")
{
DividingMethod();
break;
}
else
{
Console.WriteLine("Please type multiply or divide.");
}
}
}
public static void DividingMethod()
{
Console.Write("Enter a number to be divided");
double num01 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter a number to divide by");
double num02 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(num01 + " divided by " + num02 + " is equal to " + num01/num02);
Console.WriteLine("");
Console.ReadKey();
}
public static void MultiplyingMethod()
{
double num01;
double num02;
Console.Write("Enter a number to be multiplied");
num01 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter a numeber to multiply by");
num02 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(num01 + " multiplied by " + num02 + " equals " + num01*num02);
Console.WriteLine("");
Console.ReadKey();
}
Call a method with no parameters like MultiplyingMethod(); instead of MultiplyingMethod;. Thats no valid C#
Please don't use goto. It makes your code messy. Take a look at loops
You should call the methods with ().
Write MultiplyingMethod(); instead of MultiplyingMethod(); and
DividingMethod(); instead of DividingMethod;
public static void Main(string[] args)
{
string answer;
Console.WriteLine("Would you like to divide or multiply? Type your choice.");
Start:
answer = (Console.ReadLine());
if (answer == "multiply")
{
MultiplyingMethod();
}
else if (answer == "divide")
{
DividingMethod();
}
else
{
Console.WriteLine("Please type multiply or divide.");
goto Start;
}
}
public static void DividingMethod()
{
double num01;
double num02;
Console.Write("Enter a number to be divided");
num01 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter a number to divide by");
num02 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(num01 + " divided by " + num02 + " is equal to " + num01 / num02);
Console.WriteLine("");
Console.ReadKey();
}
public static void MultiplyingMethod()
{
double num01;
double num02;
Console.Write("Enter a number to be multiplied");
num01 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter a numeber to multiply by");
num02 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(num01 + " multiplied by " + num02 + " equals " + num01 * num02);
Console.WriteLine("");
Console.ReadKey();
}
In addition, never use goto, it is not good!
There are several issues with this code:
Calling functions should be done with the syntax: funcname(params). So DividingMethod; becomes DividingMethod();
Try not to use goto (it sounds easy but makes your code really hard to read and debug)
Too many brackets
if (answer == "multiply")
{
MultiplyingMethod;
}
{
else if (answer == "divide")
{
DividingMethod;
}
}
Should be:
if (answer == "multiply")
{
MultiplyingMethod();
}
else if (answer == "divide")
{
DividingMethod();
}

C# Console Output Formatting

I'm trying to get a factorial to be displayed as for example (factorial of 5 is 5*4*3*2*1)
I'm using a method for the factorial, but it doesn't accept the line Console.Write(i + " x "); in my code.
Any help would be great.
here is my code.
//this method asks the user to enter a number and returns the factorial of that number
static double Factorial()
{
string number_str;
double factorial = 1;
Console.WriteLine("Please enter number");
number_str = Console.ReadLine();
int num = Convert.ToInt32(number_str);
// If statement is used so when the user inputs 0, INVALID is outputed
if (num <= 0)
{
Console.WriteLine("You have entered an invalid option");
Console.WriteLine("Please enter a number");
number_str = Console.ReadLine();
num = Convert.ToInt32(number_str);
//Console.Clear();
//topmenu();
//number_str = Console.ReadLine();
}
if (num >= 0)
{
while (num != 0)
{
for (int i = num; i >= 1; i--)
{
factorial = factorial * i;
}
Console.Write(i + " x ");
Console.Clear();
Console.WriteLine("factorial of " + number_str.ToString() + " is " + factorial);
factorial = 1;
Console.WriteLine("(please any key to return to main menu)");
Console.ReadKey();
Console.Clear();
topmenu();
}
}
return factorial;
}
Thank you!
The problem is that your for loop isn't using braces, so the scope is just one line.
Try adding braces appropriately:
for (int i = num; i >= 1; i--)
{
factorial = factorial * i;
Console.Write(i.ToString() + " x ");
}
Console.WriteLine("factorial of " + number_str.ToString() + " is " + factorial);
Without the braces, the i variable only exists on the next statement (factorial = factorial * i;), and no longer exists in scope by the time you call Console.Write.
You will likely also want to remove the call to Console.Clear immediately following this Write, or you will not see it.
here's a solution to consider
public static void Main()
{
Console.WriteLine("Please enter number");
int input;
while (!int.TryParse(Console.ReadLine(), out input) || input <= 0)
{
Console.WriteLine("You have enter an invald option");
Console.WriteLine("Please enter number");
}
Console.Write("Factorial of " + input + " is : ");
int output = 1;
for (int i = input; i > 0; i--)
{
Console.Write((i == input) ? i.ToString() : "*" + i);
output *= i;
}
Console.Write(" = " +output);
Console.ReadLine();
}
int.TryParse() will be beneficial for you, so the program doesn't crash if the user inputs a non-integer
also, you may want something besides an integer. Factorials get very large very fast - anything over 16 will return a wrong result.

Categories

Resources