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;
}
Related
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();
}
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
}
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();
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.
Not sure if I'm overlooking something really simple but I'm trying to make a program that allows a user to enter 1 of 2 letters and then run code based on the input. Seems simple enough but I've run into several errors with all the ways I thought this could work. Here is the code:
string name = (Console.ReadLine());
Console.WriteLine("Is " + name + " ok?");
Console.WriteLine("\n(Y)es\n(N)o");
char ansys = Console.ReadKey();
if (ansys = ConsoleKey.Y)
Console.Clear();
else
{
Console.WriteLine();
Console.WriteLine("Enter letters only");
}
I added in the else portion (unfinished)just to get an idea if If i'm going the right direction with the intended goal as well. Would I be able to make an else statement that triggers if neither Y or N is pressed this way?
Well, first of all, you are making an assignment, not comparing:
if (ansys.Key = ConsoleKey.Y)
is wrong, use:
if (ansys.Key == ConsoleKey.X)
== is comparison, = is assignment. Don't confuse them, it may cause serious problems.
For you question, if you simply add an else if statement checking for "No" answer, then else statement won't be triggered if Y or N is pressed. If at least if statement is executed, else statement won't be executed.
Your code should look like:
if (ansys == ConsoleKey.Y) {
// code if yes
}
else if (ansys == ConsoleKey.N) {
// code if no
}
else {
// code if neither
}
Edit:
Since my primary language is not C#, I looked at documentation to check my answer. I figured out that if you use ReadKey() it does not return a ConsoleKey, it returns struct ConsoleKeyInfo. You need to use Key member of the ConsoleKeyInfo to access the pressed key. Please re-check the code.
Try this approach:
ConsoleKeyInfo cki;
cki = Console.ReadKey();
if (cki.Key == ConsoleKey.Y)
{
Console.Clear();
}
else if (cki.Key == Console.N)
{
Console.Clear();
}
else
{
Console.WriteLine();
Console.WriteLine("Enter letters only");
}
You can find th examples here: ReadKey - examples
Try this:
string name = (Console.ReadLine());
Console.WriteLine("Is " + name + " ok?");
Console.WriteLine("\n(Y)es\n(N)o");
var ansys = Console.ReadKey();
if (ansys.KeyChar == 'y' || ansys.KeyChar == 'Y')
{
//Handle yes case
}
if (ansys.KeyChar == 'n' || ansys.KeyChar == 'N')
{
//Handle no case
}
else
{
Console.WriteLine();
Console.WriteLine("Enter letters only");
}
Try this (couldnt test it)
This will ask for the name until the confirmation answer is Y
If the input when asked Y or N is another thing, it will ask again for the name confirmation.
string name = "";
while (name.equals(""))
{
name = (Console.ReadLine());
Console.WriteLine("Is " + name + " ok?");
String answer = "";
while(answer.equals(""))
{
Console.WriteLine("\n(Y)es\n(N)o");
char ansys = Console.ReadKey();
if (ansys == ConsoleKey.Y || ansys == ConsoleKey.N)
{
answer = ansys.ToString();
Console.Clear();
}
else
{
Console.WriteLine();
Console.WriteLine("Enter letters only!!");
}
}
if(!answer.equals("Y"))
name = "";
}
Im not sure if ansys.ToString() is a valid method, and if that returns the "Y" string in case the key pressed was Y