c# asking multiple questions in a loop - c#

I am very confused, this is only my second project in coding/scripting and i do not understand how to have multiple choices for a player to choose between. the loop goes back after the second or third question without continuing and it keeps skipping a few lines of code just wondering what I am doing wrong.
static void Main(string[] args)
{
Random rng = new Random();
int stuff = 0;
bool gameGo = true;
string yourAnswer = "";
string choice1 = "";
string choice2 = "";
string choice3 = "";
string choice4 = "";
int healthPoints = 100;
int deathNumber = rng.Next(0, 10);
deathNumber = deathNumber = 0;
int stabbed = rng.Next(1, 4);
string name = "";
int trap = rng.Next(1, 5);
int arrow = rng.Next(7, 14);
int menu = 0;
int potion = rng.Next(1, 10);
int flyHealth = rng.Next(5, 10);
int flyAttack = rng.Next(3, 5);
int tribeAttack = rng.Next(80, 100);
int playersSword = rng.Next (3, 5);
while(true)
{
break;
}
while (gameGo || stuff == 1 )
{
Console.Write("You have ");
Console.Write(healthPoints);
Console.Write(", health points left");
Console.Write(" \nIf your health points drops to ");
Console.Write(deathNumber);
Console.Write(", you will DIE!");
Console.WriteLine("\nWell now that that's out of the way, excuse me for being so rude but,\nmay i have your name? Please hit enter after to continue.");
name = Console.ReadLine();
Console.Clear();
if (name == "Dustin")
{
Console.Write("You have");
Console.Write(healthPoints);
Console.Write(", health points left");
Console.WriteLine("\nI am so proud of you for figuring out your name, {0}", name);
Console.WriteLine("Shall we move on to the story?\n Hit Enter to continue.");
Console.ReadLine();
menu = 2;
}
else if (name != "Dustin")
{
healthPoints -= stabbed;
Console.Clear();
Console.WriteLine("Seriously you cant figure out your name, how dumb are you?");
}
if (menu == 2)
{
Console.WriteLine("You see a cave in the distance.");
Console.WriteLine(" You have to make a choice.");
Console.WriteLine("Do you go in to explore or do you pass on by?");
Console.WriteLine("a) Do you go in\nOr B) do you pass by?");
choice1 = Console.ReadLine();
}
if (choice1 == "a")
{
Console.WriteLine("You enter a dark cave with no idea where to go but you found a sword.");
Console.WriteLine("The sword can do 1-5 damage.\n This is your only defense.");
Console.Write("\nTap enter once to continue");
Console.ReadLine();
menu = 3;
Console.Clear();
}
if (choice1 == "b")
{
Console.WriteLine("What, are you scared of the dark?");
healthPoints -= stabbed;
Console.WriteLine("A masked man stabbed you for not going in the cave and says");
Console.Write("you now have,");
Console.Write(healthPoints);
Console.Write(" health points left");
Console.WriteLine("Hit enter to continue.");
Console.ReadLine();
menu = 4;
continue;
}
{
while (menu == 3)
{
Console.WriteLine("You wander further in the cave and look around");
Console.WriteLine("You see a torch on the wall");
Console.WriteLine("You have another choice.\nDo you a) Light the torch \n or b) Leave it unlit");
choice2 = Console.ReadLine();
Console.Clear();
}
if (choice2 == "a")
{
Console.WriteLine("Well done my good sir, you have brought light to this wretched cave.");
Console.WriteLine("You move along slowly and encounter a giant fly.");
Console.Clear();
menu = 5;
}
if (choice2 == "b")
{
Console.WriteLine("What do you enjoy being in the dark?");
healthPoints -= stabbed;
Console.WriteLine("A masked man snuck up on you and stabbed you in the dark");
Console.Write("you now have,");
Console.Write(healthPoints);
Console.Write(" health points left");
Console.ReadLine();
Console.WriteLine("You move along slowly in the dark and encounter a giant fly.");
Console.ReadLine();
Console.Clear();
menu = 6;
}
}
{
while (menu == 4)
{
Console.WriteLine("You chose to keep walking along and not go into the cave.");
Console.WriteLine("You stumble across a large valley.");
Console.WriteLine("Time for another choice.");
Console.WriteLine("Do you a) Climb down the valley hoping for cool treasure?\nOR b) Keep walking along?");
choice3 = Console.ReadLine();
Console.Clear();
}
if (choice3 == "a")
{
Console.WriteLine("You decided to go into the valley");
Console.WriteLine("Little did you know there was a trap that got sprung as you climbed down");
healthPoints -= trap;
Console.Clear();
menu = 7;
}
if (choice3 == "b")
{
Console.WriteLine("How much more boring can you get, do you ever go on real adventures.");
Console.WriteLine("as you are walking along a stray arrow comes out of no where and strikes you in the leg.");
healthPoints -= arrow;
Console.Clear();
menu = 8;
}
}
{
while (menu == 5)
{
//giant fly fight
Console.Write("The giant fly swoops in to attack");
flyAttack -= healthPoints;
Console.WriteLine("The fly does {0} damage to your health", flyAttack);
Console.Write("You now have,");
Console.Write(healthPoints);
Console.Write(" health.");
Console.WriteLine("You attack back, with your sword you found");
playersSword -= flyHealth;
Console.WriteLine("You did {0} damage to the flys health points.", playersSword);
menu = 9;
}
while (menu == 6)
{
Console.Write("The giant fly swoops in to attack");
flyAttack -= healthPoints;
Console.WriteLine("The fly does {0} damage to your health", flyAttack);
Console.Write("You now have,");
Console.Write(healthPoints);
Console.Write(" health.");
Console.WriteLine("You attack back, with your sword you found");
playersSword -= flyHealth;
Console.WriteLine("You did {0} damage to the flys health points.", playersSword);
menu = 9;
}
while (menu == 7)
{
Console.WriteLine("You reach the bottom and come across a tribe of people.");
Console.WriteLine("This tribe has never seen another human before.");
Console.WriteLine("Hit enter to continue.");
Console.ReadLine();
Console.Clear();
Console.WriteLine("You hesitate for a bit wondering what to do. \nWhen all of a sudden the tribe attacks.");
healthPoints -= tribeAttack;
Console.Write("You have ");
Console.Write(healthPoints);
Console.Write(", health points left");
}
if (menu == 8)
{
//kept walking
}
if (menu == 9)
{

while loops happen until a condition is satisfied.
Something written like this (which is taken from your example above) will never stop.
while (menu == 3 {
// do stuff here, but menu never changes
}
The loop is entered when menu is 3. menu is never changed from within the loop, so it will never change from 3 - thus the loop will never exit. It will simply start back at the beginning of the loop until menu is not 3.
For further clarification, if statements cause code to be executed based on a condition. Unlike a while loop, the block of code that is executed is not looped through. If the condition is false, no code within the block is executed. If the condition is true, the code within the block is only executed once.
You'll be able to make some progress once you think about how things flow. To help with this, if you're using a modern IDE, you can set a breakpoint at the beginning and step through the program, watching how decisions are made one line at a time.

Related

Exit loop if while condition is met

I have a program that stores user input in an array.
Every time a user input is stored, the int var Counter is increased by 1.
My problem is that if i store 25 variables, the loop ends BUT lets say i enter something that is not valid, the loop continues even after the 25 variables are stored. I want to make sure that the loop ends after the while condition is met even if the program catches the error if that makes any sense.
And no, i want to use an array and not a list!
Thanks
void AddPassenger()
{
//Counts total passengers on the bus to determin if the buss is empty
Passenger.TotalPassengers = 0;
//Variable for loops
int Counter = 0;
do
{
//Adds 25 passengers with a loop
for (int i = 0; i < Passenger.Age.Length; i++)
{
Console.Clear();
Logo();
Console.WriteLine("\nEnter Age for passenger {0}", Counter + 1);
Counter++;
try
{
Passenger.Age[i] = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("Did you enter a number?\n");
Console.WriteLine("Press any key to try again...");
Counter--;
Console.ReadKey();
break;
}
//Checks if user enters a valid age
if (Passenger.Age[i] < 0 || Passenger.Age[i] > 130)
{
Console.WriteLine("Try a different age");
}
Console.WriteLine("\nEnter Gender for passenger {0}", Counter);
Console.WriteLine("1) Male");
Console.WriteLine("2) Female");
Console.WriteLine("3) Other");
//Using a temp variable to run switch for selecting gender
int temp = 0;
try
{
temp = Convert.ToInt32(Console.ReadLine());
Console.Clear();
Passenger.TotalPassengers++;
}
catch
{
Console.Clear();
Logo();
Console.WriteLine("\nNot a valid choice");
}
switch (temp)
{
case 1:
Passenger.Gender[i] = "Male";
break;
case 2:
Passenger.Gender[i] = "Female";
break;
case 3:
Passenger.Gender[i] = "Other";
break;
default:
Console.WriteLine("Did you enter a number?\n");
Console.WriteLine("Press any key to try again...");
Console.ReadKey();
Counter--;
break;
}
}
} while (Counter < 25);
This is not suppose to happen
In the scope of your question you could do something similar to the following (note this has not been run but quickly knocked up with comments)
void AddPassenger()
{
//Counts total passengers on the bus to determin if the buss is empty
Passenger.TotalPassengers = 0;
//Variable for loops
int Counter = 0;
do
{
//Adds 25 passengers with a loop
for (int i = 0; i < Passenger.Age.Length; i++)
{
// ensure we're not leaving the scope of the `while`
if(Counter >= 25)
break;
Console.Clear();
Logo();
Console.WriteLine("\nEnter Age for passenger {0}", Counter + 1);
try
{
Passenger.Age[i] = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("Did you enter a number?\n");
Console.WriteLine("Press any key to try again...");
Console.ReadKey();
break;
}
//Checks if user enters a valid age
if (Passenger.Age[i] < 0 || Passenger.Age[i] > 130)
{
Console.WriteLine("Try a different age");
break; // you needed to break here I assume
}
Console.WriteLine("\nEnter Gender for passenger {0}", Counter);
Console.WriteLine("1) Male");
Console.WriteLine("2) Female");
Console.WriteLine("3) Other");
//Using a temp variable to run switch for selecting gender
int temp = 0;
try
{
temp = Convert.ToInt32(Console.ReadLine());
Console.Clear();
Passenger.TotalPassengers++;
}
catch
{
Console.Clear();
Logo();
Console.WriteLine("\nNot a valid choice");
break; // you needed to break here I assume
}
switch (temp)
{
case 1:
Passenger.Gender[i] = "Male";
break;
case 2:
Passenger.Gender[i] = "Female";
break;
case 3:
Passenger.Gender[i] = "Other";
break;
default:
Console.WriteLine("Did you enter a number?\n");
Console.WriteLine("Press any key to try again...");
Console.ReadKey();
break;
}
Counter++; //move counter to here to only increment at the end if successful
}
} while (Counter < 25);
However, I would either change the name for Passenger or the model itself as it isn't clear why Passenger has an Array of ages or genders. Surely each passenger should be its own entity with these fields no?
Something like:
public Bus
{
public Passenger[] Passengers { get; set; }
public int TotalPassengers { get; set; }
}
public Passenger
{
public int Age { get; set; }
public string Gender { get; set; }
}
The for loop inside the while should be re-thought about. It doesn't make sense for a nested loop in this way.
There are 2 loops here, a for loop and a do-while loop. The for loop only stops if i reaches the array's limit, and the do-while loop only stops if Counter reaches 25.
You mentioned the loop continues even after 25 variables are stored. This is because the for loop restarts at 0 every time there's invalid input. Swap int i = 0 out for int i = Counter, that way, it continues where it left off.
Additionally:
You don't need 2 loops, specifically the for loop. You can remove it then replace all mentions of i with Counter, the same for break with continue. (In combination with #Tubs' answer)You also won't need if(Counter >= 25) break; in this case. Doing that effectively merges the 2 loops, instead of having 2 loops with the same function.
Console.WriteLine("\nEnter Gender for passenger {0}", Counter); doesn't add 1 to Counter, which will result in Enter Gender for passenger 0.
Extending on #Tubs' answer:
Also, Counter is only incremented after all the breaks, which means it's unreachable. You'll have to transfer to each successful case(1, 2, and 3).
The resulting code is:
void AddPassenger()
{
//Counts total passengers on the bus to determin if the buss is empty
Passenger.TotalPassengers = 0;
//Variable for loops
int Counter = 0;
//Adds 25 passengers with a loop
do
{
Console.Clear();
Logo();
Console.WriteLine("\nEnter Age for passenger {0}", Counter + 1);
try
{
Passenger.Age[i] = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("Did you enter a number?\n");
Console.WriteLine("Press any key to try again...");
Console.ReadKey();
continue;
// Continue while loop instead of breaking it
}
//Checks if user enters a valid age
if (Passenger.Age[i] < 0 || Passenger.Age[i] > 130)
{
Console.WriteLine("Try a different age");
continue;
// Continue while loop instead of breaking it
}
Console.WriteLine("\nEnter Gender for passenger {0}", Counter + 1);
Console.WriteLine("1) Male");
Console.WriteLine("2) Female");
Console.WriteLine("3) Other");
//Using a temp variable to run switch for selecting gender
int temp = 0;
try
{
temp = Convert.ToInt32(Console.ReadLine());
Console.Clear();
Passenger.TotalPassengers++;
}
catch
{
Console.Clear();
Logo();
Console.WriteLine("\nNot a valid choice");
continue;
// Continue while loop instead of breaking it
}
switch (temp)
{
case 1:
Passenger.Gender[i] = "Male";
// Increment after success
Counter++;
continue;
// Continue while loop instead of breaking it
case 2:
Passenger.Gender[i] = "Female";
// Increment after success
Counter++;
continue;
// Continue while loop instead of breaking it
case 3:
Passenger.Gender[i] = "Other";
// Increment after success
Counter++;
continue;
// Continue while loop instead of breaking it
default:
Console.WriteLine("Did you enter a number?\n");
Console.WriteLine("Press any key to try again...");
Console.ReadKey();
continue;
// Continue while loop instead of breaking it
}
} while (Counter < 25);

implementing a play again feature in a random number guess generator

I have been doing some programming exercises in university lately and i came across one that wanted the user to guess between the numbers 1 and 100. They also want it to have the ability to let the user play again. When first ran the program is fine but when i say 'y' to play again it generates the same number i previously guessed:
I found some solutions however there was so much spaghetti code i couldn't read it on websites. is there any way to save a few lines of code.
here is my source:
int guess = 0;
Random r1 = new Random();
int answer = r1.Next(1, 100);
bool finished = false;
while (!finished)
{
Console.WriteLine("please guess a number between 1 - 100");
guess = int.Parse(Console.ReadLine());
if (guess < answer)
{
Console.WriteLine("your answer is too low please try again!");
}
else if (guess > answer)
{
Console.WriteLine("your answer is too high please try again!");
}
else if (guess == answer)//nested
{
Console.WriteLine("your answer is correct!");
Console.WriteLine("answer:" + answer);
Console.WriteLine("Play again? ('y' or 'n')");
string playAgain = null;
playAgain = Console.ReadLine();
if (playAgain == "n")
{
finished = true;
}
}//end of nested else
}//end of while
The reason why the same number is being given every time to guess is that you do not generate it if the user wants to continue the game, but instead you use what was already declared.
else if (guess == answer)//nested
{
Console.WriteLine("your answer is correct!");
Console.WriteLine("answer:" + answer);
Console.WriteLine("Play again? ('y' or 'n')");
string playAgain = null;
playAgain = Console.ReadLine();
if (playAgain == "n")
{
finished = true;
}
answer = r1.Next(1,100);
}//end of nested else
If you want to get rid of some lines, then you can simply declare some variable inside of the loop.
Random r1 = new Random();
int answer = r1.Next(1, 100);
while (true)
{
Console.WriteLine("please guess a number between 1 - 100");
guess = int.Parse(Console.ReadLine());
if (guess < answer)
{
Console.WriteLine("your answer is too low please try again!");
}
else if (guess > answer)
{
Console.WriteLine("your answer is too high please try again!");
}
else if (guess == answer)//nested
{
Console.WriteLine("your answer is correct!");
Console.WriteLine("answer:" + answer);
Console.WriteLine("Play again? ('y' or 'n')");
if (Console.ReadLine() == "n")
{
break; // stop the loop
}
}//end of nested else
}//end of while
Because before restarting the guess, the field "answer" is always the previously generated random value "54". Therefore, if the user enters "y", you can add a statement to reset the value of "answer".
// code omitted
// ...
// reset answer
if(playAgain == "y")
{
answer = r1.Next(1, 100);
}
if (playAgain == "n")
{
finished = true;
}

Error detected trying to receive input as an integer in C#

I am trying to make a simple program where the user tries to guess numbers between 1 and 25 until they guess the right one. I am trying to make the input received as an integer so that I can use greater than and less than signs. When I use the command I found on another answer in this forum, it says that there is an error. What am I doing wrong?
int score = 0;
int add = 1;
while (add == 1)
{
Console.WriteLine("Guess A Number Between 1 and 25");
string input = int.Parse(Console.ReadLine());
score += add;
if (input == 18)
{
Console.WriteLine("You Did It!");
Console.WriteLine("Your Score was " + score);
break;
}
else if (input > 25)
{
Console.WriteLine("Error.");
}
else
{
Console.WriteLine("Try Again. Score: " + score);
}
}
Store their response from ReadLine() as a String, then use int.TryParse() to attempt to convert that String to an Integer. The code below is written to show you all the possible states that could occur using if else blocks. I've also used a bool to indicate when the game should end instead of using a break statement:
static void Main(string[] args)
{
int number;
string input;
bool guessed = false;
int score = 0;
while (!guessed)
{
Console.Write("Guess A Number Between 1 and 25: ");
input = Console.ReadLine();
if (int.TryParse(input, out number))
{
if(number>=1 && number<=25)
{
score++;
if (number == 18)
{
guessed = true;
Console.WriteLine("You Did It!");
Console.WriteLine("Your Score was " + score);
}
else
{
Console.WriteLine("Try Again. Score: " + score);
}
}
else
{
Console.WriteLine("Number must be between 1 and 25!");
}
}
else
{
Console.WriteLine("That's not a number!");
}
Console.WriteLine();
}
Console.Write("Press Enter to Quit.");
Console.ReadLine();
}

my if/else if statment makes me input multiple times before running

So when I run the code I can press 1 and that runs fine but when I try entering 2 or 3 then the computer makes me enter 2 or 3 multiple times before running that line of code.
I don't know what the problem with this is.
I'm new so if there is a better way to run something like this instead of if statements please let me know.
using System;
namespace PracticeScript
{
class Program
{
static void Main()
{
Random rnd = new Random();
int playerHp = 100;
int enemyHp = 100;
int playerD = rnd.Next(10, 15);
int enemyD = rnd.Next(10, 15);
int potion = 25;
Console.Write("Get Ready! It's time to battle! ");
Console.WriteLine("You stare into the eyes of the ugly goblin and are ready to slay it with your sword \n");
do
{
Console.WriteLine(" what will you do now?");
Console.WriteLine("\n 1. Attack 2. Defend 3. Use potion");
if (Console.ReadLine() == "1")
{
enemyHp -= playerD;
Console.WriteLine("you swung your sword and struck the goblin in the body leaving it " + enemyHp + "HP left over");
}
else if (Console.ReadLine() == "2")
{
Console.WriteLine("You prepaired your sheild for the incoming attack");
}
else if (Console.ReadLine() == "3")
{
playerHp += potion;
Console.WriteLine("You chugged down the potion as quick as you could and now have " + playerHp + " left!" );
}
Console.WriteLine("\nEnemy Turn!");
playerHp -= enemyD;
Console.WriteLine("The goblin struck you with his mace and left you with " + playerHp + "HP left!");
} while (playerHp > 0 || enemyHp > 0);
You need to store the result of Console.ReadLine before testing its value:
string line = Console.ReadLine();
if (line == "1")
{
enemyHp -= playerD;
Console.WriteLine("you swung your sword and struck the goblin in the body leaving it " + enemyHp + "HP left over");
}
else if (line == "2")
{
Console.WriteLine("You prepaired your sheild for the incoming attack");
}
else if (line == "3")
{
playerHp += potion;
Console.WriteLine("You chugged down the potion as quick as you could and now have " + playerHp + " left!" );
}
Otherwise your program will call Console.ReadLine 3 times and prompt the user 3 times in the worst case.
Console.ReadLine() will prompt for input every time you call it.
You can use a switch statement instead to ask for input once and compare it against every value you want to handle:
switch (Console.ReadLine())
{
case "1":
// ...
break;
case "2":
// ...
break;
// Add rest of cases here
}
Basically, you are evaluating each Console.Readline() each time the user enters a value. So, user enter 2, if (Console.ReadLine() == "1") evaluates to false. Enters 2 again, else if (Console.ReadLine() == "2") evaluates to true. As others have stated, use Console.ReadLine() once per loop, store the value, and check it in your if statements:
string userinput = Console.ReadLine();
if(userinput == "1")
// do stuff
else if(userinput == "2")
// do other stuff
//etc.
I suggest you to use a switch
The problem was the fact that you repeated 3 time Console.ReadLine() instead of storing and using its value!
Plus, I added a check of the user input, you didn't think about the possibility to have an invalid input!
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int playerHp = 100;
int enemyHp = 100;
int playerD = rnd.Next(10, 15);
int enemyD = rnd.Next(10, 15);
int potion = 25;
Console.Write("Get Ready! It's time to battle! ");
Console.WriteLine("You stare into the eyes of the ugly goblin and are ready to slay it with your sword \n");
do
{
Console.WriteLine(" what will you do now?");
Console.WriteLine("\n 1. Attack 2. Defend 3. Use potion");
bool isInputValid = false;
while (isInputValid == false)
{
isInputValid = true;
switch (Console.ReadLine())
{
case "1":
enemyHp -= playerD;
Console.WriteLine("you swung your sword and struck the goblin in the body leaving it " + enemyHp + "HP left over");
break;
case "2":
Console.WriteLine("You prepaired your sheild for the incoming attack");
break;
case "3":
playerHp += potion;
Console.WriteLine("You chugged down the potion as quick as you could and now have " + playerHp + " left!");
break;
default:
Console.WriteLine("Invalid input, please choose a listed action!");
isInputValid = false;
break;
}
}
Console.WriteLine("\nEnemy Turn!");
playerHp -= enemyD;
Console.WriteLine("The goblin struck you with his mace and left you with " + playerHp + "HP left!");
} while (playerHp > 0 || enemyHp > 0);
}
}

How to allow user to quit console app at any time?

Can someone help me make the option to quit the app at anytime work in this code? Also, I was wondering why I have to hit enter twice for the message "That is not an integer" when the user enters a string instead of a number?
using System;
using System.Threading;
namespace farino_HighLow
{
public class Game
{
// TAKES AND TRACKS USER INPUT
public void PlayGame()
{
// CREATES VARIABLE FOR INPUT FROM THE USER (IF THEY MAKE AN INVALID GUESS OR WANT TO EXIT),
// THE RANDOM VALUE GENERATED, THE USERS GUESS, AND A COUNTER FOR HOW MANY GUESSES THE USER TAKES
Random random = new Random();
int returnValue = random.Next(1, 100);
string input;
string line;
int guess = 0;
int count = 0;
Console.Beep(1000, 2000);
// INSTRUCTS USER WHAT TO DO
Console.WriteLine("Guess a number between 1-100");
Console.WriteLine("Hit Q at any time to exit the game");
do
{
input = Console.ReadLine();
try
{
guess = Convert.ToInt32(input);
}
catch
{
if (input == "Q")
{
break;
}
}
line = Console.ReadLine();
if (!int.TryParse(line, out guess))
Console.WriteLine("Not an integer!");
// MAKES SURE USER ENTERS A NUMBER WITHIN THE PARAMETERS OF THE GAME
// COUNTS THE USER GUESSES
// TELLS USER IF THEIR GUESS WAS RIGHT OR WRONG AND DIRECTS THEM TOWARDS A BETTER GUESS
if (guess >= 1 && guess <= 100)
{
if (guess > returnValue)
{
Console.Beep(100,2000);
Console.WriteLine("Guess Again! Your guess is too HIGH");
count += 1;
}
if (guess < returnValue)
{
Console.Beep(300,2000);
Console.WriteLine("Guess Again! Your guess is too LOW");
count += 1;
}
if (guess == returnValue)
{
Console.Beep(50,2000);
Console.Beep(60,2000);
Console.Beep(70,2000);
Console.WriteLine("You got it RIGHT!!!!!!");
count += 1;
Console.WriteLine("It took you" + count + "guesses to win the game.");
}
if (guess < 1)
{
Console.WriteLine("That is not a valid entry");
}
if (guess > 100)
{
Console.WriteLine("That is not a valid entry");
}
}
} while (guess != returnValue);
Thread.Sleep(5000);
Console.Clear();
}
}
}
Try This code
using System;
using System.Threading;
namespace farino_HighLow
{
public class Game
{
// TAKES AND TRACKS USER INPUT
public void PlayGame()
{
// CREATES VARIABLE FOR INPUT FROM THE USER (IF THEY MAKE AN INVALID GUESS OR WANT TO EXIT),
// THE RANDOM VALUE GENERATED, THE USERS GUESS, AND A COUNTER FOR HOW MANY GUESSES THE USER TAKES
Random random = new Random();
int returnValue = random.Next(1, 100);
string input;
string line;
int guess = 0;
int count = 0;
Console.Beep(1000, 2000);
// INSTRUCTS USER WHAT TO DO
Console.WriteLine("Guess a number between 1-100");
Console.WriteLine("Hit Q at any time to exit the game");
do
{
input = Console.ReadLine();
try
{
guess = Convert.ToInt32(input);
}
catch
{
if (input == "Q")
{
//after press Q exit from application
return;
}
}
line = Console.ReadLine();
if (!int.TryParse(line, out guess))
Console.WriteLine("Not an integer!");
// MAKES SURE USER ENTERS A NUMBER WITHIN THE PARAMETERS OF THE GAME
// COUNTS THE USER GUESSES
// TELLS USER IF THEIR GUESS WAS RIGHT OR WRONG AND DIRECTS THEM TOWARDS A BETTER GUESS
if (guess >= 1 && guess <= 100)
{
if (guess > returnValue)
{
Console.Beep(100, 2000);
Console.WriteLine("Guess Again! Your guess is too HIGH");
count += 1;
}
if (guess < returnValue)
{
Console.Beep(300, 2000);
Console.WriteLine("Guess Again! Your guess is too LOW");
count += 1;
}
if (guess == returnValue)
{
Console.Beep(50, 2000);
Console.Beep(60, 2000);
Console.Beep(70, 2000);
Console.WriteLine("You got it RIGHT!!!!!!");
count += 1;
Console.WriteLine("It took you" + count + "guesses to win the game.");
}
if (guess < 1)
{
Console.WriteLine("That is not a valid entry");
}
if (guess > 100)
{
Console.WriteLine("That is not a valid entry");
}
}
} while (guess != returnValue);
Thread.Sleep(5000);
Console.Clear();
}
}
}
Simply use either: Environment.Exit(0); or Application.Exit();
if(condition is true)
{
Environment.Exit(0);
}
else
{
//continue
}

Categories

Resources