So I made a basic game for a school assignment. One of the requirements is, to let program choose who is playing first, either the computer or the player. So I wrote an if/else statement then put my code inside of it. The code works, but then I added code which limits what numbers the player can input. Those numbers range from 1-3. If a players inputs a number less than one or greater than three they get an error message. After my if/else executed which picks the player who goes first, it stops working and only picks the player and not the computer. Is there a way to fix this?
int chips = 21, user, computer;
int pickPlayer;
Random rn = new Random();
pickPlayer = rn.Next(1, 5);
if (pickPlayer == 1 || pickPlayer == 2 || pickPlayer == 3 )
{
//Player goes First
while (chips > 0)
{
Console.WriteLine("There are {0} Chips Choose Either 1,2,3 chips", chips);
user = Convert.ToInt32(Console.ReadLine());
if (user > 3 || user <= 0)
{
Console.WriteLine("You can only take between 1 and 3 chips. Try again");
}
else
{
chips = chips - user;
Random rnd = new Random();
/*if (chips <= 0)
{
Console.WriteLine("You Lose");
Console.ReadLine();
} */
}
if (chips <= 0)
{
Console.WriteLine("You Lose");
Console.ReadLine();
}
}
}
else
{
//Computer goes first
while (chips > 0)
{
Console.WriteLine("There are {0} Chips Choose Either 1,2,3 or 4 chips", chips);
Random rnd = new Random();
computer = rnd.Next(1, 4);
user = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Computer picks {0} chips", computer);
chips = chips - computer;
if (chips <= 0)
{
Console.WriteLine("You Lose");
Console.ReadLine();
}
else
{
if (user > 3 || user <= 0)
{
Console.WriteLine("You can only take between 1 and 3 chips. Try again");
}
else
{
chips = chips - user;
/*if (chips <= 0)
{
Console.WriteLine("You Win");
Console.ReadLine();
} */
}
if (chips <= 0)
{
Console.WriteLine("You Win");
Console.ReadLine();
}
}
}
}
Try this.
I corrected the algorithm and I refactored the code using anonymous methods and changing names but you can create class methods instead.
I used int.TryParse instead of Convert so it returns only a number or 0 in case of error.
Random random = new Random();
int chipsStart = 21;
int chipsCurrent = chipsStart;
int playerTake;
int computerTake;
bool playerFirst = random.Next(0, 2) == 0;
Func<bool> processPlayer = () =>
{
Console.WriteLine("There are {0} Chips Choose Either 1,2,3 chips", chipsCurrent);
do
{
int.TryParse(Console.ReadLine(), out playerTake);
}
while ( playerTake == 0 );
if ( playerTake < 1 || playerTake > 3 )
Console.WriteLine("You can only take between 1 and 3 chips. Try again");
else
chipsCurrent = chipsCurrent - playerTake;
if ( chipsCurrent > 0 )
return true;
else
{
Console.WriteLine("You Lose");
return false;
}
};
Func<bool> processComputer = () =>
{
computerTake = random.Next(1, 4);
Console.WriteLine("Computer picks {0} chips", computerTake);
chipsCurrent = chipsCurrent - computerTake;
if ( chipsCurrent > 0 )
return true;
else
{
Console.WriteLine("You Win");
return false;
}
};
if ( playerFirst )
while ( true )
{
if ( !processPlayer() ) break;
if ( !processComputer() ) break;
}
else
while ( true )
{
if ( !processPlayer() ) break;
if ( !processComputer() ) break;
}
Console.ReadLine();
Related
Whenever input is outside of range 1-4 its supposed to throw an Invalid entry text and ask for another input, however when you type in another input, the program error's out and doesn't continue. I'm not sure where I am going wrong. I am using C# and this is an assignment that requires me to use the do while loop for this section.
static void Main(string[] args)
{
Write("Enter a salespersons name: ");
string salesPerson = ReadLine();
int intItem;
int intQuantity;
double item1 = 239.99;
double item2 = 129.75;
double item3 = 99.95;
double item4 = 350.89;
double dblItemSales;
double dblTotalSales;
do
{
Write("Enter an item number between 1 and 4 or -1 to quit: ");
intItem = Convert.ToInt32(ReadLine());
if ( intItem < 1 || intItem > 4 )
{
WriteLine("Invalid Entry");
Write("Enter an item number between 1 and 4 or -1 to quit: ");
intItem = Convert.ToInt32(ReadLine());
}
else if ( intItem == -1 )
{
WriteLine("Salesperson " + salesPerson + " sold a total of ");
break;
}
else
Write("Enter the quantity sold: ");
intQuantity = Convert.ToInt32(ReadLine());
}
while ( intItem != -1 );
WriteLine("Press Enter to Continue.");
ReadLine();
}
static void Main(string[] args)
{
Write("Enter a salespersons name: ");
string salesPerson = ReadLine();
int intItem;
int intQuantity;
double item1 = 239.99;
double item2 = 129.75;
double item3 = 99.95;
double item4 = 350.89;
double dblItemSales;
double dblTotalSales;
do
{
Write("Enter an item number between 1 and 4 or -1 to quit: ");
if (Int32.TryParse(ReadLine(), out intItem))
{
if (intItem == -1)
{
WriteLine("Salesperson " + salesPerson + " sold a total of ");
break;
}
else if (intItem < 1 || intItem > 4)
{
WriteLine("Invalid Entry");
}
else
{
Write("Enter the quantity sold: ");
if (!Int32.TryParse(ReadLine(), out intQuantity))
{
intQuantity = 0; // or whatever
}
}
}
}
while (intItem != -1);
WriteLine("Press Enter to Continue.");
ReadLine();
}
Since -1 < 1 it is the very first branch
if ( intItem < 1 || intItem > 4 ) // true when intItem == -1
{
...
}
else if ( intItem == -1 ) // this branch will never be executed
which runs. Put it like this:
while (true) { // keep looping until explicit quit
Write("Enter an item number between 1 and 4 or -1 to quit: ");
if (!int.TryParse(ReadLine(), out var intItem)) // what if user put "bla-bla-bla"?
Write("Syntax error. Integer 1..4 expected");
else if (intItem == -1) { // quit
WriteLine("Salesperson " + salesPerson + " sold a total of ");
break;
}
else if (intItem < 1 || intItem > 4) { // invalid range
WriteLine("Invalid Entry");
Write("Enter an item number between 1 and 4 or -1 to quit:");
}
else { // main routine
// intItem is integer in 1..4 range
Write("Enter the quantity sold: ");
//TODO: put relevant code here
}
}
You can try such thing, depending of what you want to do with quantities entered hence I put something for the sample:
bool isValid;
do
{
Console.Write("Enter an item number between 1 and 4 or -1 to end: ");
int.TryParse(Console.ReadLine(), out intItem);
if ( intItem == -1 ) break;
if ( intItem < 1 || intItem > 4 )
{
Console.WriteLine("Invalid entry: try again, please.");
continue;
}
dblItemSales++;
do
{
Console.Write("Enter the quantity sold: ");
isValid = int.TryParse(Console.ReadLine(), out intQuantity) && intQuantity >= 0;
if ( !isValid )
Console.WriteLine("Invalid entry: try again, please.");
}
while ( !isValid );
dblTotalSales += intQuantity;
}
while ( true );
Console.WriteLine($"Sales person {salesPerson} sold a total of {dblTotalSales}" +
$" for {dblItemSales} items");
Console.WriteLine("Press Enter to Continue.");
We use TryParse to ensure that a number is entered else it is 0 and the method rertuens false.
In case you don't want to change the current code. Short fix:
Move this intQuantity = Convert.ToInt32(Console.ReadLine()); line inside the else statement.
Delete this codes inside if statement:
Write("Enter an item number between 1 and 4 or -1 to quit: ");
intItem = Convert.ToInt32(ReadLine());
It should be look like this:
do
{
Console.Write("Enter an item number between 1 and 4 or -1 to quit:");
intItem = Convert.ToInt32(Console.ReadLine());
if (intItem< 1 || intItem> 4)
{
Console.WriteLine("Invalid Entry");
}
else if (intItem == -1)
{
Console.WriteLine("Salesperson " + salesPerson + " sold a total of ");
break;
}
else
{
Console.Write("Enter the quantity sold: ");
intQuantity = Convert.ToInt32(Console.ReadLine());
}
}
while (intItem != -1);
Console.WriteLine("Press Enter to Continue.");
Console.ReadLine();
I am trying to make a program to play a game of craps where the user enters a bet amount, then they roll 2 six sided dice. If the sum of the dice s 2,3 or 12 they lose. 7 or 11 they win. if any other number is rolled the player keeps rolling until they get the point number to win or 7 to lose. However for some reason if I select n to not play again it still loops the game a second time before quitting. I am not sure why
any help would be appreciated.
static void processCraps()
{
string gameStatus = null;
double betAmount =0;
double netWinning = 0;
int point;
do
{
try
{
Console.WriteLine("Enter the amount to bet");
betAmount = double.Parse(Console.ReadLine());
}
catch (Exception)
{
Console.WriteLine("Invaid input try again");
}
var diceRoll = RollDice();
if (diceRoll == 2 || diceRoll == 3 || diceRoll == 12)
{
Console.WriteLine($"You lost {betAmount}");
netWinning = netWinning - betAmount;
}
else if (diceRoll == 7 || diceRoll == 11)
{
Console.WriteLine($"You won {betAmount}");
netWinning = netWinning + betAmount;
}
else if (diceRoll != 2 || diceRoll != 3 || diceRoll != 12 || diceRoll != 7 || diceRoll != 11)
{
point = diceRoll;
Console.WriteLine($"Point is {point}");
for (int rollCount = 0; rollCount >= point; rollCount++)
{
var roll = RollDice();
if (roll == 7)
{
Console.WriteLine($"You lost {betAmount}");
netWinning = netWinning - betAmount;
}
else if (roll == point)
{
Console.WriteLine($"You won {betAmount}");
netWinning = netWinning + betAmount;
}
}
}
try
{
Console.WriteLine("Do you want to play again (y/n)");
gameStatus = Console.ReadLine();
}
catch (Exception)
{
Console.WriteLine("answer must be a letter");
}
} while (gameStatus != "n") ;
Console.WriteLine($"Your net winning is {netWinning}");
}
You read input twice.
You may want to split the logic into two loops. 1. Read bet amount. 2. Play game.
do
{
Console.WriteLine("Enter the amount to bet, or 'q' to quit:");
var betStr = Console.ReadLine();
if( betStr == "q") return;
double.TryParse(betStr, out betAmount);
} while (betAmount != 0);
do
{
//Play
Console.WriteLine("Do you want to play again (n = quit)?");
gameStatus = Console.ReadLine();
} while (gameStatus != "n");
I am programming a game that generates a random number and then has the user try to guess the number when the user inputs a number the program will respond with either too high or too low depending on the number generated.The problem I am having is that the loop will just keep executing and the program will not take another user input if the number is incorrect.I have tried using different types of loops like a do while and for loop but keep getting the same problem I feel as though I am missing something simple or making a simple mistake thanks
string usernumber;
Random rnd = new Random();
int value = rnd.Next(1,50); //generates a random number upto 50
int guess = 0;
Console.WriteLine("please enter a number"); //asks for and takes user input
usernumber = Console.ReadLine();//stores user input
guess = Convert.ToInt32(usernumber);
while (guess != value) //this stands for not equals to
{
//guess = Convert.ToInt32(usernumber);
if (value > guess)
{
Console.WriteLine("too high");
}
else if (value < guess)
{
Console.WriteLine("too low");
}
else if (value == guess)
{
Console.WriteLine("bang on the answer was" + value);
}
else
{
Console.WriteLine("errrrrrrrrr");
}
}
Thread.Sleep(2000); //delays the program closing for a bit
You can use this corrected and refactored to have more explicit variables names.
We add 1 to 50 because the Random.Next last parameter is the upper bound excluded.
We use a do...while loop to have a concise algorithm.
We use int.TryParse to get the int from the user. This method returns false and sets the value to 0 in case of conversion error instead of an exception.
We use Console.ReadKey instead of Thread.Sleep, that is more UX friendly.
var random = new Random();
int numberTarget = random.Next(1, 50 + 1);
int numberUser;
do
{
Console.Write("Please enter a number between 1 and 50: ");
if ( int.TryParse(Console.ReadLine(), out numberUser) )
{
if ( numberUser > numberTarget )
{
Console.WriteLine("Too high, retry.");
}
else
if ( numberUser < numberTarget )
{
Console.WriteLine("Too low, retry.");
}
else
{
Console.WriteLine($"Bang on the answer was {numberTarget}.");
}
}
else
{
Console.WriteLine("You didn't enter a valid number, retry.");
}
}
while ( numberUser != numberTarget );
Console.WriteLine("Press a key to exit.");
Console.ReadKey();
In your while loop, you forgot to make another ReadLine.
while (guess != value) //this stands for not equals to
{
if (value > guess)
{
Console.WriteLine("too high");
guess = Convert.ToInt32(Console.ReadLine());
}
else if (value < guess)
{
Console.WriteLine("too low");
guess = Convert.ToInt32(Console.ReadLine());
}
else if (value == guess)
{
Console.WriteLine("bang on the answer was" + value);
}
else
{
Console.WriteLine("errrrrrrrrr");
}
}
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...");
}
My code works for the most part, I tried finding a solution online but struggled to find my exact issue. Here's the code, in C#:
static void Main(string[] args)
{
int maxFilm = 5;
int minFilm = 1;
Console.WriteLine("We are currently showing:");
Console.WriteLine("1. Rush");
Console.WriteLine("2. How I live now");
Console.WriteLine("3. Thor");
Console.WriteLine("4. Filth");
Console.WriteLine("5. Planes");
const int minAge1 = 15;
const int minAge2 = 12;
const int minAge3 = 18;
int filmNumber;
string filmNum;
int age;
string stringAge;
do
{
Console.WriteLine("Enter the number of the film you wish to see: ");
filmNum = Console.ReadLine();
filmNumber = Int32.Parse(filmNum);
if (filmNumber > maxFilm || filmNumber < minFilm)
{
Console.WriteLine("Invalid film number");
}
}
while (filmNumber > maxFilm || filmNumber < minFilm);
do
{
Console.WriteLine("Enter your age: ");
stringAge = Console.ReadLine();
age = Int32.Parse(stringAge);
if (age < 5 || age > 120)
{
Console.WriteLine("Invalid age");
}
} while (age < 5 || age > 120);
if (((filmNumber == 1 || filmNumber == 2) && age >= minAge1) || (filmNumber == 3 && age >= minAge2) || (filmNumber == 4 && age >= minAge3) || (filmNumber == 5))
{
Console.WriteLine("Enjoy the film");
}
else
{
Console.WriteLine("You are too young");
}
Input:
First, invalid movie number
Second, valid movie number
Third, age between 5-120
Expected output: Either "You are too young" or "enjoy the film" and then the code exits
What happens: The code exits and then re-executes from the start.
If I put a valid film number to start with, then it performs as expected. Any help is appreciated
After your final Console.WriteLine(), add a Console.ReadLine()
Example:
Console.WriteLine("Enjoy the film");
Console.ReadLine();
Also if you don't want the program to close after this, I suggest putting the program into a loop.
I assume that you want to see out put, so you can use following code :
Console.ReadLine();
or
Console.ReadKey();
To put entire code. generally, in loop is not good idea.