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");
}
}
}
Related
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!");
}
}
}
}
}
I'm having issues creating a program that is a number guessing program. I think I have the written part right but possibly not the order of it? I have to use multiple methods such as a method for number generator of the number that is supposed to be guessed, a method for collecting the guess input, and method for checking the guess to see if it's right. I've literally have tried just about everything for days but all I get is rather a repeat of, "Enter the number: " even if its right, although it's supposed to repeat if it's too high or low. Or sometimes the console won't print anything. what is wrong? Here is the code:
using System;
namespace GuessTheNumber
{
class Program
{
public static int RandomNumberGenerator()
{
Random random = new Random();
return random.Next(1, 21);
}
public static int InputGetter()
{
Console.Write("Enter in a number: ");
int guess = Convert.ToInt32(Console.ReadLine());
return guess;
}
public static String GuessChecker(int guess, int secretNumber)
{
if(guess > secretNumber)
{
return "Too high!";
}
else if (guess < secretNumber)
{
return "Too low!";
}
else
{
return "Correct";
}
}
static void Main(string[] args)
{
int secretNumber = 10;
Console.WriteLine("" + secretNumber);
while (true)
{
while (InputGetter() != secretNumber)
{
InputGetter();
GuessChecker(InputGetter(), secretNumber);
}
if (GuessChecker(InputGetter(), secretNumber) == ("Correct!"))
{
Console.WriteLine("Would you like to play again?");
String input = Console.ReadLine();
if (GuessChecker(InputGetter(), secretNumber) == ("Yes"))
{
secretNumber = RandomNumberGenerator();
}
else if (GuessChecker(InputGetter(), secretNumber) == ("No"))
{
break;
}
}
}
}
}
}
You are invoking InputGetter() multiple times and your logic is incorrect.
It has nothing to do with Random instance being used.
I have quickly modified your code and it should work now as follows:
New number is generated, if you enter low/high message is displayed, if you enter correct number you are presented with the Would you like to try again message.
EDIT: I did not want to change original code much,In general Comparing strings is bad, you should not use it. Creating enum like and comparing would be much better
class Program
{
public static int RandomNumberGenerator()
{
Random random = new Random();
var generatedNumber = random.Next(1, 21);
Console.WriteLine($"New Number generated! {generatedNumber}");
return generatedNumber;
}
public static int InputGetter()
{
Console.Write("Enter in a number: ");
int guess = Convert.ToInt32(Console.ReadLine());
return guess;
}
public static String GuessChecker(int guess, int secretNumber)
{
if (guess > secretNumber)
{
Console.WriteLine("Too High");
return "Too high!";
}
else if (guess < secretNumber)
{
Console.WriteLine("Too low!");
return "Too low!";
}
else
{
Console.WriteLine("Correct");
return "Correct";
}
}
static void Main(string[] args)
{
int secretNumber = 10;
Console.WriteLine("" + secretNumber);
while (true)
{
int enteredNumber = 0;
do
{
enteredNumber = InputGetter();
} while (GuessChecker(enteredNumber, secretNumber)!="Correct");
Console.WriteLine("Would you like to play again?[Yes/No]");
String input = Console.ReadLine();
if (input=="Yes")
{
secretNumber = RandomNumberGenerator();
}
else
{
break;
}
}
}
}
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...");
}
I'm very sorry this is such an easy question, I'm just starting out. I've created code that allows a user to enter a number of random dice rolls, and outputs the sum of those rolls. I've now been asked to create a loop that repeats these steps, including the prompt, until the user types 'quit'. My issue is that my code converts the string to an integer, so typing anything kills the code. Any tips of how to insert the loop and break? My code is:
static void Main(string[] args)
{
Random random = new Random();
Console.WriteLine("Enter a number of dice to roll:");
string numberDiceString = Console.ReadLine();
int numberDice = Convert.ToInt32(numberDiceString);
int total = 0;
for (int index = 0; index < numberDice; index++)
{
int DieRoll = random.Next(6) + 1;
total += DieRoll;
}
Console.WriteLine(total);
Console.ReadKey();
}
I wouldn't use a "while(true)" statement. As someone pointed out in the comments i would prefer using the right condition in there.
That being said i would do it this way:
static void Main(string[] args)
{
Random random = new Random();
string numberDiceString;
int numberDice;
Console.WriteLine("Enter a number of dice to roll:");
while ((numberDiceString = Console.ReadLine()) != "quit")
{
bool parsed = int.TryParse(numberDiceString, out numberDice);
if (!parsed)
{
//Handle the error. The user input was not a number or "quit" word
break;
}
int total = 0;
for (int index = 0; index < numberDice; index++)
{
int DieRoll = random.Next(6) + 1;
total += DieRoll;
}
Console.WriteLine(total);
Console.WriteLine("Enter a number of dice to roll:");
}
}
I have to say that i prefer this way because you can easily see when the loop will stop. Also i added an error handling that you should be doing (What happen if the user enters any words that are not numbers?).
Hope this helps.
This change should be fairly simple. What you need to do is to create a while loop, and then a check before you actually parse for an int. The psuedocode for this would be something like.
while(true) {
//Ask for input
//Check if it equals "quit"
//If so -> break;
//If not convert to int
//For Loop for dice rolls
//Print Total
}
I'm sure it could be a little more elegant than this, and you would want to put some more checks to make sure that invalid input doesn't crash the program, but it should get the job done.
This is a very simple solution that shows how to parse the user input.
using System;
namespace Simpleton
{
class Program
{
static public int GetChoice()
{
int choice = 0;
while (true)
{
Console.Write("Enter number of rolls or \"quit\" to finish: ");
var answer = Console.ReadLine();
if (String.Compare(answer, "quit", true) == 0)
{
return 0; // Done
}
if (Int32.TryParse(answer, out choice))
{
return choice;
}
}
}
static void Main(string[] args)
{
var choice = 0;
while ((choice = GetChoice()) > 0)
{
Console.WriteLine($"You'll be looping {choice} times.");
for (int tries = 0; tries < choice; tries++)
{
// Looping
}
}
}
}
}
Try this code:
static void Main(string[] args)
{
Random random = new Random();
while(true)
{
String numberDiceString = "";
int numberDice = 0;
Console.WriteLine("Enter a number of dice to roll:");
numberDiceString = Console.ReadLine();
if (numberDiceString == "quit") { return; }
int total = 0;
if (Int32.TryParse(numberDiceString, out numberDice))
{
total = 0;
for (int index = 0; index < numberDice; index++)
{
int DieRoll = random.Next(6) + 1;
total += DieRoll;
}
}
Console.WriteLine(total);
}
}
I'm not a C# programmer, but you can test for "quit" explicitly and use a goto
BeginLoop:
Console.WriteLine("Enter a number of dice to roll:");
string numberDiceString = Console.ReadLine();
if (numberDiceString == "quit")
{
goto EndLoop;
}
int numberDice = Convert.ToInt32(numberDiceString);
/* Rest of code you want to do per iteration */
goto BeginLoop;
EndLoop:
Brand new to C# [4 hours new :)], but hoping for some pointers on a Board Feet Calculator restricting the user input to only numbers, not allow letters or special characters.
First, does the restriction take place in the Class, Method, and/or Program? (I believe Class and Method)
Second, I've seen an example below, would I use something similar to this?
Third, if so, do I need to make separate classes for KeyPress and KeyPressEventArgs? (I believe they automatically there e.g.
public char KeyChar { get; set; }
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// allows only letters
if (!char.IsLetter(e.KeyChar))
{
e.Handled = true;
}
}
My Program
namespace BoardFt_MyTry_
{
class Program
{
static void Main(string[] args)
{
Board board = new Board();
board.lengthOfboard = Convert.ToDouble(askQuestion("What is the length of your board in inches?"));
board.widthOfboard = Convert.ToDouble(askQuestion("What is the width of your board in inches?"));
board.thicknessOfboard = Convert.ToDouble(askQuestion("What is the thickness of your board in inches?"));
Console.WriteLine("Your board has {0} board feet.", board.CalcBoardFt());
Console.ReadLine();
}
private static string askQuestion(string question)
{
Console.WriteLine(question);
return Console.ReadLine();
}
}
My Board Class
namespace BoardFt_MyTry_
{
class Board
{
public double lengthOfboard;
public double widthOfboard;
public double thicknessOfboard;
public double CalcBoardFt()
{
double boardft = 0;
boardft = (this.lengthOfboard * this.widthOfboard * this.thicknessOfboard) / 144;
return boardft;
}
}
}
You can't really do that in a console application. All you can do is allow the user to input the bad data, then tell the user that the data is bad.
You can try something like this:
class Program
{
public double AskDnoubleQuestion(string message){
do {
Console.Write(message);
var input = Console.ReadLine();
if (String.IsNullOrEmpty(input)){
Console.WriteLine("Input is required");
continue;
}
double result;
if (!double.TryParse(input, out result)){
Console.WriteLine("Invalid input - must be a valid double");
continue;
}
return result;
}
static void Main(string[] args)
{
Board board = new Board();
board.lengthOfboard = AskDoubleQuestion("What is the length of your board in inches?");
board.widthOfboard = AskDoubleQuestion(askQuestion("What is the width of your board in inches?");
board.thicknessOfboard = AskDoubleQuestion(askQuestion("What is the thickness of your board in inches?");
Console.WriteLine("Your board has {0} board feet.", board.CalcBoardFt());
Console.ReadLine();
}
In case validation is not the way you want to proceed, you could do something like this:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number:");
string number = ReadNumber();
Console.WriteLine("You entered: " + number);
}
private static string ReadNumber()
{
string input = "";
do
{
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
if (char.IsNumber(keyInfo.KeyChar))
{
input = input + keyInfo.KeyChar;
Console.Write(keyInfo.KeyChar);
}
if (keyInfo.Key == ConsoleKey.Enter)
{
Console.WriteLine();
break;
}
if (keyInfo.Key == ConsoleKey.Backspace)
{
input = input.Substring(0, input.Length - 1);
Console.Write("\b \b");
}
} while (true);
return input;
}
}
This will allow the user to enter only numbers. You could filter it anyway you want, if you wanted to. For example, only letters and numbers, etc...
As it stands right now, it only allows integer numbers. If you want to allow a decimal point, change the line above to this: if (char.IsNumber(keyInfo.KeyChar) || keyInfo.KeyChar == '.')
You could write a method that reads key by key (not displaying in the console), ignores non-numeric characters, prints valid characters and appends them to a StringBuilder instance, like so:
public static string ReadOnlyNumbers()
{
StringBuilder input = new StringBuilder();
ConsoleKeyInfo ckey;
while ((ckey = Console.ReadKey(true)).Key != ConsoleKey.Enter)
{
if (Char.IsDigit(ckey.KeyChar))
{
Console.Write(ckey.KeyChar);
input.Append(ckey.KeyChar);
}
if (ckey.Key == ConsoleKey.Backspace)
{
input.Length--;
Console.Write("\b \b");
}
}
Console.Write(Environment.NewLine);
return input.ToString();
}
You could then use it like this:
string input = ReadOnlyNumbers();
Console.WriteLine(input);