How to allow user to quit console app at any time? - c#

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
}

Related

how to stop my code from looping at the end?

i'm new at coding C# pls help me fix this simple dice game, it keeps on looping at the end of the game
** apparently how i think is that in the end of this code something makes the NO commend on looping and getting re runed**
using System;
namespace first_game
{
class Program
{
static void Main(string[] args)
{
string userName;
userName = Console.ReadLine();
#region
{
int userPoint = 0;
int cpuPoint = 0;
int pDice;
bool closeApp;
while (true)
{
while (cpuPoint < 10 && userPoint < 10)
{
Random rd = new Random();
pDice = rd.Next(1, 6);
#endregion
int P2Dice;
Random scondRd = new Random();
P2Dice = scondRd.Next(1, 6);
Console.ReadLine();
Console.WriteLine("-------------------");
Console.Write("playe dice:");
Console.WriteLine(pDice);
Console.Write("CPU dice:");
Console.WriteLine(P2Dice);
Console.ReadLine();
if (pDice > P2Dice)
{
userPoint = userPoint + 1;
}
else if (pDice < P2Dice)
{
cpuPoint = cpuPoint + 1;
}
Console.Clear();
Console.WriteLine(userName);
Console.Write("player point:");
Console.WriteLine(userPoint);
Console.Write("CPU point:");
Console.Write(cpuPoint);
Console.ReadLine();
}
if (userPoint == 10)
{
Console.WriteLine("-----------------\nYOU WIN!!!");
Console.ReadLine();
}
else
{
Console.WriteLine("-----------------\nYOU lost!!! LOL");
Console.ReadLine();
}
Console.WriteLine("wanna continue?\n press Y for yes press N for NO");
ConsoleKeyInfo sw;
sw = Console.ReadKey();
Console.Clear();
if (sw.Key == ConsoleKey.Y)
{
userPoint = 0;
cpuPoint = 0;
continue;
}
else if (sw.Key == ConsoleKey.N)
{
}
else
Console.WriteLine("ERROR!");
}
}
}
}
}
You seem to have the wrong idea about continue. A while loop always (given a true condition) reruns if it reaches the end, a continue just starts the next iteration early.
else if (sw.Key == ConsoleKey.N) { }
else Console.WriteLine("ERROR!");
This is where you should exit the loop, for example using a break
else if (sw.Key == ConsoleKey.N) {
break;
} else Console.WriteLine("ERROR!");
Add a break to exit the while loop:
if (userPoint == 10)
{
Console.WriteLine("-----------------\nYOU WIN!!!");
break;
}
else
{
Console.WriteLine("-----------------\nYOU lost!!! LOL");
break;
}
Then add this after the while loop, so that the console doesn't close:
Console.ReadLine();

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

Try/Catch and loop

1)After try and catch i want to loop it again to give new number("Console.ReadLine("Give correct number"))because user does not entered string convertable to double
2Second problem is, when user give wrong number i would like to loop again to enter new number. This version of program give message to small or to big number and exit
corrected
double number=10,11;
Console.WriteLine("Give a number");
string w=Console.ReadLine();
try
{
double d = Convert.ToDouble(w);
}
catch(FormatException)
{
Console.WriteLine("it is not a number");
}
double dd=Convert.ToDouble(w);
if (dd == number)
{
Console.WriteLine("Yes, it is!");
}
else if (number<dd)
{
Console.WriteLine("to big number");
}
else if(number>dd)
{
Console.WriteLine("to small number");
}
Console.ReadLine();
First, use a do..while(condition) to keep asking until the user enters a valid number. Second, use TryParse to check if the value is valid. This is better than exception handling and converting it twice. Not sure why you are using doubles, but ints might be more appropriate.
bool valid = false;
do
{
bool newValidState;
Console.WriteLine("Give a number");
string w = Console.ReadLine();
double d;
if (!double.TryParse(w, out d))
{
Console.WriteLine("it is not a number");
newValidState = false;
}
else if (d == number)
{
Console.WriteLine("Yes, it is!");
newValidState = true;
}
else if (wyliczona < wybor) // these conditions seem unrelated to `d`
// are they okay?
{
Console.WriteLine("to big number");
newValidState = false;
}
else if(wyliczona > wybor)
{
Console.WriteLine("to small number");
newValidState = false;
}
else
{
Console.WriteLine("unknown condition. needs work.");
newValidState = false;
}
valid = newValidState;
}
while (!valid);
Note the use of newValidState, which will make sure you always assign a new value to valid. This helps to prevent endless loops due to never setting a value. The code will not compile unless every branch sets newValidState to a value.
Try this one:
var number =3;
do{
Console.WriteLine("Give a number");
string w=Console.ReadLine();
try
{
double d = Convert.ToDouble(w);
}
catch(FormatException)
{
Console.WriteLine("it is not a number");
continue; // not a number starting new iteration of the loop
}
double dd=Convert.ToDouble(w);
if (dd == number)
{
Console.WriteLine("Yes, it is!");
break; // The number guessed exiting loop
}
else if (dd>number)
{
Console.WriteLine("to big number");
}
else if(dd<number)
{
Console.WriteLine("to small number");
}
}
while (true);
Console.ReadLine();

How to solve error CS0103: the name 'minutes' does not exist in the current context

I am currently doing a tree-house course in which you create a fitness console app that records your input exercise time , tallies it and gives you feedback depending on your and have received no help in the treehouse community , so if anyone could help me find a solution to the following it would be great help , im not sure if it has something to do with where the variable is placed , if it is in-between the braces in which in is called. Im not too sure im really new to this
using System;
namespace Treehouse.fitnessFrog
{
class Program
{
static void Main()
{
int runningTotal = 0;
bool keepGoing = true;
while(keepGoing) {
// Prompt user for minutes exercised
Console.Write("Enter how many minutes you exercised or type quit to exit ");
string entry = Console.ReadLine();
if(entry == "quit")
{
keepGoing = false;
}else{
try
{
int minutes = int.Parse(entry);
if(minutes <= 0)
{
Console.WriteLine("Not Acceptable");
continue;
}
else if(minutes <= 10)// Number 1
{
Console.WriteLine("Better than nothing, am I right ?");
}
else if(minutes <= 30) // Number 2
{
Console.WriteLine("You are still quite lazy");
}
else if(minutes <= 60) // Number 3
{
Console.WriteLine("Your doing all right i guess. But work on you're spelling!");
}
else
{
Console.WriteLine("Cool story bro");
}
}
catch(FormatException)
{
Console.WriteLine("That is not valid");
continue;
}
// Add minutes exercised to total
runningTotal = runningTotal + minutes;
// Display total minutes exercised to the screen
Console.WriteLine("You've entered "+ runningTotal + " minutes");
// Repeat until user quits
}
}
Console.WriteLine("Goodbye mate");
}
}
}
You should declare variable minutes outside try block:
int minutes = 0; // create variable here
try
{
minutes = int.Parse(entry); // here only use this variable
if(minutes <= 0)
{
// your code
}
//else if statements
...
}

Categories

Resources