Guessing Game C# Enter - c#

I have a question, how to set the condition that if the user presses "Enter" when guessing a number, the program would ask "Enter a number"!
Program randomNumberA = new Program();
int r = randomNumberA.RandomNumber();
do
{
Console.WriteLine("Take a guess.\n");
string n = userNumberA.UserNumber();
int num;
int.TryParse(n, out num);
ConsoleKeyInfo key = Console.ReadKey();
if (IsAllDigits(n))
{
if (num > r)
{
Console.WriteLine("Your guess is too high!\n");
userGuess++;
}
if (num < r)
{
Console.WriteLine("Your guess is too low!\n");
userGuess++;
}
if (num == r)
{
Console.WriteLine($"Good job, {name}! You guessed my number in {userGuess} guesses!");
break;
}
}
else if (!IsAllDigits(n) || string.IsNullOrEmpty(n) || !char.IsNumber(key.KeyChar))
{
Console.WriteLine("Please enter the correct number!");
continue;
}
} while (userGuess <= USER_LIMIT);
if (userGuess > USER_LIMIT)
{
Console.WriteLine("Game Over!");
}
This logic checks the game, but still does not work if the user presses the "Enter" button

The code you've posted is slightly incomplete, but you're comparing the result of userNumberA.UserNumber() to r and not using key until the very last else if condition, which is confusing.
I think your logic can be changed slightly. Here is a sample with some hard-coded values that you should be able to leverage in your existing code:
private static Random _random = new Random();
static void Main(string[] args)
{
// Pick a random number between 1 and 100 for the user to guess
int secretNumber = _random.Next(1, 101);
int USER_LIMIT = 3;
int userGuess = 0;
Console.Write("Please enter your name: ");
string name = Console.ReadLine();
while (userGuess < USER_LIMIT)
{
userGuess++;
Console.Write("Guess a number between 1 and 100: ");
int num;
if (int.TryParse(Console.ReadLine(), out num))
{
if (num > secretNumber)
{
Console.WriteLine("Your guess is too high!\n");
}
else if (num < secretNumber)
{
Console.WriteLine("Your guess is too low!\n");
}
else
{
Console.WriteLine($"\nGood job, {name}! That only took {userGuess} guesses!");
break;
}
}
else
{
Console.WriteLine("Please enter a valid number!");
}
}
Console.WriteLine("\nGame Over!");
if (userGuess == USER_LIMIT) Console.WriteLine($"\nThe number was: {secretNumber}");
GetKeyFromUser("\nDone! Press any key to exit...");
}

Related

C# Play Again Number Game

I'm trying to implement the ability for the user to input Y or N to play the game again or exit, but I'm struggling to get my head round it without a massive rewrite of the code logic... I'm just getting back into C# today and am a beginner so please go easy on me :) I've already got the userContinue string ready and just want to enter a simple way of repeating the game and adding on ways of keeping score (slowly improving the game)
using System;
namespace Guess_Number_V2
{
class Program
{
static void Main(string[] args)
{
do
{
PlayGame();
Console.WriteLine("Would you play to play again? Y or N");
} while (Console.ReadLine().ToLower() == "y");
}
public static voic PlayGame()
{
Random rand = new Random();
int randNum = rand.Next(1, 11);
int incorrectGuesses = 0;
int userScore = 10;
int userGuess;
int perGuess = 1;
string userContinue;
bool correctGuess = false;
Console.WriteLine("Enter a number between 1 and 10\nScore starts at 10, one point will be deducted with each incorrect guess.");
userGuess = int.Parse(Console.ReadLine());
while (correctGuess == false)
{
if (userGuess == randNum)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Your guess was right, the number was {0}! Total score is {1} and you had {2} incorrect guesses.", randNum, userScore, incorrectGuesses);
correctGuess = true;
}
if (userGuess > randNum)
{
userScore -= perGuess;
incorrectGuesses++;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Wrong guess again, to high!");
correctGuess = false;
}
else if (userGuess < randNum)
{
userScore -= perGuess;
incorrectGuesses++;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Wrong guess again, to low!");
correctGuess = false;
}
}
}
}
}
It would help if you put your game logic in its own method. Say PlayGame(). Then you can simply write:
static void Main(string[] args)
{
do {
PlayGame();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Would you play to play again? Y or N");
} while (Console.ReadLine().ToLower() == "y");
}
Also, you can simplify your logic if you make an "infinite" loop and break out of it with break; when the guess is correct.
You can read and parse the user input at the beginning of each loop.
Setting the user score the number of incorrect guesses and the red console color can be done only once also.
Tested and working code:
using System;
namespace Guess_Number_V2
{
class Program
{
static void Main(string[] args)
{
do {
PlayGame();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Would you play to play again? Y or N");
} while (Console.ReadLine().ToLower() == "y");
}
private static void PlayGame()
{
Random rand = new Random();
int randNum = rand.Next(1, 11);
int incorrectGuesses = 0;
int userScore = 10;
int userGuess;
int perGuess = 1;
Console.WriteLine("Enter a number between 1 and 10\nScore starts at 10, one point will be deducted with each incorrect guess.");
while (true) {
userGuess = int.Parse(Console.ReadLine());
if (userGuess == randNum) {
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Your guess was right, the number was {0}! Total score is {1} and you had {2} incorrect guesses.", randNum, userScore, incorrectGuesses);
break;
}
userScore -= perGuess;
incorrectGuesses++;
Console.ForegroundColor = ConsoleColor.Red;
if (userGuess > randNum) {
Console.WriteLine("Wrong guess again, to high!");
} else { // Must be userGuess < randNum
Console.WriteLine("Wrong guess again, to low!");
}
}
}
}
}

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

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

Changing ConsoleKeyInfo into int

I am new to the programing c#. I tried to program a simple program that would run in cmd. I thought that it would randomly creat a noumber and the user would put in the numbers and he/she would try to guess the randomly created one. The program would tell you if it is lower or higher then the number you putted in... I started programing but I came to the problem... I can not compare noumber putted in by user and the randomly generated one.
This is the code...
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Guess the number!");
Random randomObject = new Random();
int RandNoumber = randomObject.Next(9999) + 1;
ConsoleKeyInfo keyinfo = Console.ReadKey();
if (keyinfo < RandNoumber) //This is where I got an error msg
{
}
}
}
Thank you for all the support!
MP
You could use Consol.ReadLine and then parse the value the user entered
static void Main(string[] args)
{
Console.WriteLine("Guess the number!");
Random randomObject = new Random();
int RandNoumber = randomObject.Next(9999) + 1;
int enteredNumber;
while (true)
{
bool parsed = int.TryParse(Console.ReadLine(), out enteredNumber);
if (parsed)
{
if (enteredNumber < RandNoumber)
{
Console.WriteLine("Wrong it's higher");
}
else if (enteredNumber > RandNoumber)
{
Console.WriteLine("Wrong it's lower");
}
else
{
Console.WriteLine("Good Job!");
//Do victory dance
return;
}
}
else
{
Console.WriteLine("Please enter a number");
}
}
}

Breaking out of a loop when user inputs quit or exit c#

I'm having trouble with looping my program so that it breaks out of the loop if user enters "quit" or "exit".
When I type any string, my program crashes as it tries to parse the string input to an int. Any advice?
namespace DiceRolling
{
/* We’re going to write a program that makes life easier for the player of a game like this. Start the
program off by asking the player to type in a number of dice to roll.Create a new Random
object and roll that number of dice.Add the total up and print the result to the user. (You should
only need one Random object for this.) For bonus points, put the whole program in a loop and allow them to keep typing in numbers
until they type “quit” or “exit”. */
class DiceRolling
{
static void RollDice(int numTries)
{
Random random = new Random();
//Console.Write("Please enter the number of dice you want to roll: ");
//int numTries = Convert.ToInt32(Console.ReadLine());
int sum = 0;
int dieRoll;
for (int i = 1; i <= numTries; i++)
{
dieRoll = random.Next(6) + 1;
Console.WriteLine(dieRoll);
sum += dieRoll;
}
Console.WriteLine("The sum of your rolls equals: " + sum);
}
static void Main(string[] args)
{
while (true)
{
Console.Write("Please enter the number of dice you want to roll: ");
string input = Console.ReadLine();
int numTries = Convert.ToInt32(input);
//bool isValid = int.TryParse(input, out numTries);
RollDice(numTries);
Console.ReadKey();
if (input == "quit" || input == "exit")
break;
}
}
}
}
Tigrams is pretty close, this is slightly better
Console.Write("Please enter the number of dices you want to roll: ");
string input = Console.ReadLine();
while (input != "quit" && input != "exit")
{
int numTries = 0;
if (int.tryParse(input, out numTries)
{
RollDice(numTries);
}
Console.Write("Please enter the number of dices you want to roll: ");
input = Console.ReadLine();
}
tried to make it as similar as possible to what you have
while (true)
{
Console.Write("Please enter the number of dices you want to roll: ");
string input = Console.ReadLine();
int numTries;
if (int.TryParse(input, out numTries))
{
RollDice(numTries);
}
else if(input == "quit" || input == "exit")
{
break;
}
}
while (true)
{
Console.Write("Please enter the number of dices you want to roll: ");
string input = Console.ReadLine();
if (input == "quit" || input == "exit") //check it immediately here
break;
int numTries = 0;
if(!int.TryParse(input, out numTries)) //handle not valid number
{
Console.WriteLine("Not a valid number");
continue;
}
RollDice(numTries);
Console.ReadKey();
}
Try int numTries =int.Parse(input != null ? input: "0");

Invalid expression term 'else' after i typed it the second time

static void Main(string[] args)
{
Console.WriteLine("what is the value of 3 + 8?");
number = int.Parse(Console.ReadLine());
if (number == 11)
{
Console.WriteLine("well done");
Console.WriteLine("press enter once");
Console.ReadLine();
}
else;
{
Console.WriteLine("its 11 u idiot!!!");
Console.ReadLine();
}
Console.WriteLine("what is the value of 23132-23131?");
number = int.Parse(Console.ReadLine());
if (number == 1);
{
Console.WriteLine("oh yeah!");
Console.ReadLine();
}
else;
{
Console.WriteLine("u r such a noob!");
Console.ReadLine();
}
}
What is the problem there??? Visual studio told me invalid expression term 'else' after the second 'else' i typed and i don't know why?
Remove the semicolon after each of the two else keywords:
else // was else;
and after the if line:
if (number == 1) // was if (number == 1);
In addition, you should actually declare number:
var number = int.Parse(Console.ReadLine());
This is the final version of code that should work:
static void Main(string[] args)
{
Console.WriteLine("what is the value of 3 + 8?");
var number = int.Parse(Console.ReadLine());
if (number == 11)
{
Console.WriteLine("well done");
Console.WriteLine("press enter once");
Console.ReadLine();
}
else
{
Console.WriteLine("its 11 u idiot!!!");
Console.ReadLine();
}
Console.WriteLine("what is the value of 23132-23131?");
number = int.Parse(Console.ReadLine());
if (number == 1)
{
Console.WriteLine("oh yeah!");
Console.ReadLine();
}
else
{
Console.WriteLine("u r such a noob!");
Console.ReadLine();
}
}
Do it like this
int number;
Console.WriteLine("what is the value of 3 + 8?");
number = int.Parse(Console.ReadLine());
if (number == 11)
{
Console.WriteLine("well done");
Console.WriteLine("press enter once");
Console.ReadLine();
}
else
{
Console.WriteLine("its 11 u idiot!!!");
Console.ReadLine();
}
Console.WriteLine("what is the value of 23132-23131?");
number = int.Parse(Console.ReadLine());
if (number == 1)
{
Console.WriteLine("oh yeah!");
Console.ReadLine();
}
else
{
Console.WriteLine("u r such a noob!");
Console.ReadLine();
}

Categories