I am making a random number guessing game which the computer thinks of a number between 1-100. It then asks you what it is and tells you if you are right or wrong. However, whenever I debug, it says that it is higher or lower than the actual random number for some reason. Plus, it says two of those statements at once. Also, I'm not sure how to say how many guesses the person has taken. Here is my unsuccessful code.
static void Main(string[] args)
{
Random random = new Random();
int returnValue = random.Next(1, 100);
int Guess = 0;
Console.WriteLine("I am thinking of a number between 1-100. Can you guess what it is?");
while (Guess != returnValue)
{
Guess = Convert.ToInt32(Console.Read());
while (Guess < returnValue)
{
Console.WriteLine("No, the number I am thinking of is higher than " + Guess + " . Can you guess what it is?");
Console.ReadLine();
}
while (Guess > returnValue)
{
Console.WriteLine("No, the number I am thinking of is lower than " + Guess + " . Can you guess what it is");
Console.ReadLine();
}
}
while (Guess == returnValue)
{
Console.WriteLine("Well done! The answer was " + returnValue);
Console.ReadLine();
}
}
You're using a lot of unneeded iteration. The while statement takes a Boolean condition just like an IF statement.
static void Main(string[] args)
{
Random random = new Random();
int returnValue = random.Next(1, 100);
int Guess = 0;
Console.WriteLine("I am thinking of a number between 1-100. Can you guess what it is?");
while (Guess != returnValue)
{
Guess = Convert.ToInt32(Console.ReadLine());
if (Guess < returnValue)
{
Console.WriteLine("No, the number I am thinking of is higher than " + Guess + ". Can you guess what it is?");
}
else if (Guess > returnValue)
{
Console.WriteLine("No, the number I am thinking of is lower than " + Guess + ". Can you guess what it is?");
}
}
Console.WriteLine("Well done! The answer was " + returnValue);
Console.ReadLine();
}
Try to restructure the logic so it does exactly what you want.
Random r = new Random();
int val = r.Next(1, 100);
int guess = 0;
bool correct = false;
Console.WriteLine("I'm thinking of a number between 1 and 100.");
while (!correct)
{
Console.Write("Guess: ");
string input = Console.ReadLine();
if (!int.TryParse(input, out guess))
{
Console.WriteLine("That's not a number.");
continue;
}
if (guess < val)
{
Console.WriteLine("No, the number I'm thinking is higher than that number.");
}
else if (guess > val)
{
Console.WriteLine("No, the number I'm thinking is lower than that number.");
}
else
{
correct = true;
Console.WriteLine("You guessed right!");
}
}
Try making the whiles ifs instead. Such as:
if (Guess < returnValue)
{
Console.WriteLine("No, the number I am thinking of is higher than " + Guess + " . Can you guess what it is?");
}
if (Guess > returnValue)
{
Console.WriteLine("No, the number I am thinking of is lower than " + Guess + " . Can you guess what it is");
}
You also might want to put the:
Console.WriteLine("I am thinking of a number between 1-100. Can you guess what it is?");
prompt inside the while loop so it will keep asking you before each prompt.
you need to change your While loops to if-then-else statements
a while will run its code as long as the statement is true.
so, in your code, you run the first one--basically forever because you are not resetting either of the values in your condition.
if your while loop WERE to exit, then you have the same problem with the other while loops.
you want something like this:
if ( guess > myValue ) { // do something }
else ( guess < myValue ) {//do something else}
else { // do a third thing }
As others have said, you are misusing while where if is really neeeded.
static void Main(string[] args)
{
Random random = new Random();
int returnValue = random.Next(1, 100);
int Guess = 0;
int numGuesses = 0;
Console.WriteLine("I am thinking of a number between 1-100. Can you guess what it is?");
while (Guess != returnValue)
{
Guess = Convert.ToInt32(Console.Read());
string line = Console.ReadLine(); // Get string from user
if (!int.TryParse(line, out Guess)) // Try to parse the string as an integer
Console.WriteLine("Not an integer!");
else {
numGuesses++;
if (Guess < returnValue)
{
Console.WriteLine("No, the number I am thinking of is higher than " + Guess + " . Can you guess what it is?");
}
if (Guess > returnValue)
{
Console.WriteLine("No, the number I am thinking of is lower than " + Guess + " . Can you guess what it is");
}
}
}
Console.WriteLine("Well done! The answer was " + returnValue + ".\nYou took " + numGuesses + " guesses.");
}
Dude...
int total = 1,
low = 0,
high = 0;
int ranNum1,
guess;
string guessStr;
Random ranNumGen = new Random();
ranNum1 = ranNumGen.Next(1, 10);
Console.Write("Enter your guess >> ");
guessStr = Console.ReadLine();
guess = Convert.ToInt16(guessStr);
while (guess != ranNum1 )
{
while (guess < ranNum1)
{
Console.WriteLine("Your guess is to low, try again.");
Console.Write("\nEnter your guess >> ");
guessStr = Console.ReadLine();
guess = Convert.ToInt16(guessStr);
++total;
++low;
}
while (guess > ranNum1)
{
Console.WriteLine("Your guess is to high, try again.");
Console.Write("\nEnter your guess >> ");
guessStr = Console.ReadLine();
guess = Convert.ToInt16(guessStr);
++total;
++high;
}
}
//total = low + high;
Console.WriteLine("It took you {0} guesses to correctly guess {1}", total, ranNum1);
Generates a random number between 1 and 9 (including 1 and 9). Ask the user the user to get the number, then tell them whether they guessed too low or too high, or exactly right.Extras:keep the game going until the user type ‘exit’ keep track of how many guesses the user has taken, and when the game ends, print this out.
Hello maybe it's okay for you but for the other who want to try :
using System;
namespace Exemple
{
class Program
{
static void Main(string[] args)
{
Random random = new Random();
int returnvalue = random.Next(1, 51);
Console.WriteLine(" Guess a number between 1 to 51 ");
int response = Convert.ToInt32(Console.ReadLine());
while (response > returnvalue)
{
Console.WriteLine($"No the number is low than {response} try again !");
response = Convert.ToInt32(Console.ReadLine());
}
while (response < returnvalue)
{
Console.WriteLine($"No the number is high than {response} try again !");
response = Convert.ToInt32(Console.ReadLine());
}
while (response != returnvalue)
{
Console.WriteLine($" wrong answer {response} is not the good response try again !");
response = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine($"Good ! Its {returnvalue}");
}
}
}
Related
I'm creating a little number guessing game for class and I have a question that my prof still hasn't spoken about:
In my if-statements I have different messages telling the player when the guess is < random number, > the random number and == the random number. Now I would like to also print a message when the guess is too far off the random number;
If the random number is 700 and my guess is more than 100 off, how do I put this in the if-statement? I have of course tried guess + >100 but that obviously doesn't work. Do I need a new variable for this?
You can do something like this.
if (Math.Abs(guessedNumber - randomNumber)> 100){
Console.WriteLine("Your number is so far from the random number")
}
Either your guess will be 100 bigger or smaller then your number.
int randomNr = 350;
int guess = 250;
int maxOff = 100;
if (guess - randomNr > maxOff || randomNr - guess > maxOff)
{
//Show message.
}
Always try to include your code when asking a question.
Without having your code, this is a potential solution to your question :
1. Print message telling by how much the guess is off
int diff;
diff = random - guess;
if(diff > 0)
{
Console.WriteLine($"guess is smaller by {diff}");
}
else if(diff < 0)
{
Console.WriteLine($"Guess is greater by {diff}");
}
You can try this
public static int rand = new Random().Next(0, 999);
public static string myNumber;
static void Main(string[] args)
{
Console.WriteLine("Guess the random number");
do
{
myNumber = Console.ReadLine();
IHopeIguessRandomNumber(Convert.ToInt32(myNumber));
}
while (Convert.ToInt32(myNumber) != rand);
}
public static void IHopeIguessRandomNumber(int myGuess)
{
if ( myGuess == rand)
{
Console.WriteLine("You're right! This is the right number");
}
else if (myGuess <= rand - 100)
{
Console.WriteLine("Too Low! Your number is < random");
}
else if ( myGuess < rand)
{
Console.WriteLine("Your number is < random");
}
else if (myGuess >= rand + 100)
{
Console.WriteLine("Too Big! Your number is > random");
}
else if (myGuess > rand)
{
Console.WriteLine("Your number is > random");
}
}
Have a nice day :)
You can use a NESTED IF block like this.
if(guessNum < randomNum)
{
if(guessNum < randomNum - 100)
{
Console.WriteLine("The guessed number is too Low");
}
else
{
Console.WriteLine("The guessed number is Low, but you are close");
}
}
else if(guessNum > randomNum)
{
if(guessNum > randomNum + 100)
{
Console.WriteLine("The guessed number is too High");
}
else
{
Console.WriteLine("The guessed number is High, but you are close");
}
}
I can help you with the exact answer if you add the existing code snippet.
sorry if this is a repeat question or sounds pretty stupid, but I'm really new to c# and looked throughout the forum and couldn't find anything that I could actually understand.
So I'm trying to write a simple program where the user tries to guess a number between 1 and 25. Everything works except that each run of the loop instead of updating the score from the last run of the loop, like 0+1=1, 1+1=2, 2+1=3, each time it adds 1 to 0. Here is my code. How do I fix this? Thank you!
int score = 0;
int add = 1;
while (add == 1)
{
Console.WriteLine("Guess A Number Between 1 and 25");
string input = Console.ReadLine();
if (input == "18")
{
Console.WriteLine("You Did It!");
Console.WriteLine("Not Bad! Your Score was " + score + add);
break;
}
else
{
Console.WriteLine("Try Again. Score: " + score + add);
}
}
You need to actually add add to score. Try something like this:
int score = 0;
int add = 1;
while (add == 1)
{
Console.WriteLine("Guess A Number Between 1 and 25");
string input = Console.ReadLine();
score += add; // add `add` to `score`. This is the same as `score = score + add;`
if (input == "18")
{
Console.WriteLine("You Did It!");
Console.WriteLine("Not Bad! Your Score was " + score);
break;
}
else
{
Console.WriteLine("Try Again. Score: " + score);
}
}
I have created a console application where the user has 5 tries to guess number between 1 and 100. After 5 guesses the game ends, but I don’t know how to introduce at the 5th wrong intent something like “you have achieved maximum of guesses! The answer was number (X). I have tried different ways ,but is not working. This is my program
using System;
namespace Guessing_Game_4
{
class Program
{
static void Main(string[] args)
{
var number = new Random().Next(1, 100);
Console.WriteLine("Try and guess any number between 1-100. You have 5 guesses Max!");
for (var i = 0; i < 5; i++)
{
int guess = Convert.ToInt32(Console.ReadLine());
if (guess == number)
{
Console.WriteLine("You got it!");
break;
}
else
{
Console.WriteLine(guess + " is not correct! Try again!");
}
}
}
}
}
Here some Sample code
This might help
for( i=10;i>0 ; i--) {
System.out.println(" === you have " + i +" Guesses left ===");
int guess = scanner.nextInt();
if (random_number < guess) System.out.println("Smaller than guess " + guess);
if (random_number > guess) System.out.println("Greater than guess " + guess);
if (random_number == guess)
{
result = true;
break;
}
}
if (result)
{
System.out.println("You WON in "+(10-i) +" tries ");
System.out.println("******* CONGRATULATIONS **************************************");
System.out.println("*********************** YOU WON **********************");
}
else
{
System.out.println("The random number was "+random_number);
System.out.println("************************** OPPS You loose **************************************** ");
System.out.println("You are near it TRY Next time ************ GOOD LUCK ");
System.out.println("You are near it TRY Nexttime***********NEXTTIME********");
}
}
If that's all your program does, you can do the following trick. Print your message after the for loop, but now the problem is that you get the message in all cases. The trick is to return from the Main (instead of breaking the loop) on a correct guess:
Console.WriteLine("You got it!");
return;
If you've some other code to execute that returning from Main won't be a good solution, you can do the following:
Create a variable before the for loop. Let's call it isCorrectAnswer and set it to false in the beginning.
At the point where he answers correctly, set isCorrectAnswer to true before breaking the loop.
After the loop, check for that variable:
if (!isCorrectAnswer)
{
Console.WriteLine($"you have achieved maximum of guesses! The answer was number {number}.");
}
You have to have an int outside of your loop like this : int wrongAnswersCount = 0;
When the user enter a wrong number you
should add one unit to your variable wrongAnswersCount++;
In the start of the loop, you should check if the user reached the maximum amount of gueses or not, if yes break the loop and say the answer.
Your code will be something like this :
using System;
namespace Guessing_Game_4
{
class Program
{
static void Main(string[] args)
{
var number = new Random().Next(1, 100);
Console.WriteLine("Try and guess any number between 1-100. You have 5 guesses Max!");
int wrongAnswersCount = 0;
for (var i = 0; i < 5; i++)
{
if(wrongAnswersCount == 5)
{
Console.WriteLine($"you have achieved maximum of guesses! The answer was number {number}");
break;
}
int guess = Convert.ToInt32(Console.ReadLine());
if (guess == number)
{
Console.WriteLine("You got it!");
break;
}
else
{
Console.WriteLine(guess + " is not correct! Try again!");
wrongAnswersCount++;
}
}
}
}
}
class Program
{
static void Main(string[] args)
{
var number = new Random().Next(1, 100);
Console.WriteLine("Try and guess any number between 1-100. You have 5 guesses Max!");
for (var i = 0; i < 5; i++)
{
int guess = Convert.ToInt32(Console.ReadLine());
if (guess == number && i!=5)
{
Console.WriteLine("You got it!");
break;
}
else
{
Console.WriteLine(guess + " is not correct! Try again!");
}
}
Console.WriteLine(" the maximam guse");
}
}
//Try this one
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
}
This question already has answers here:
How to loop a Console App
(6 answers)
Closed 6 years ago.
I wanted to try how the if conditional works so I created this code almost by myself. I also had problems with random into int.
Here's my code:
using System;
namespace Bigger_Smaller_Equal
{
class Program
{
static void Main(string[] args)
{
int min = 1;
int max = 100;
Random rnd = new Random();
int gen = rnd.Next(min, max);
Console.WriteLine("My Number is : " + gen + "!");
Console.WriteLine("Tell me your number:");
string typ = Console.ReadLine();
int num = int.Parse(typ);
if (num == gen)
{
Console.WriteLine(num + " is Equal to " + gen);
}
else if (num > gen)
{
Console.WriteLine(num + " Is Bigger than " + gen);
}
else if (num < gen)
{
Console.WriteLine(num + " Is Smaller than " + gen);
}
Console.WriteLine("Press Any Key to exit.");
Console.ReadLine();
}
}
}
How to make the console stop, so it will allow me to enter another number?
Basically:
I write a number it tells me if its smaller bigger or equal to number which was randomly generated
After I press enter instead of closing the console the number will be generated again and I can write new number and so on.
Here's an example using goto, although it is not recommended for more complex applications as you could end up creating endless loops. Feel free to try it out
static void Main(string[] args)
{
int min = 1;
int max = 100;
Random rnd = new Random();
again:
int gen = rnd.Next(min, max);
Console.WriteLine("My Number is : " + gen + "!");
Console.WriteLine("Tell me your number:");
string typ = Console.ReadLine();
int num = int.Parse(typ);
if (num == gen)
{
Console.WriteLine(num + " is Equal to " + gen);
}
else if (num > gen)
{
Console.WriteLine(num + " Is Bigger than " + gen);
}
else if (num < gen)
{
Console.WriteLine(num + " Is Smaller than " + gen);
}
repeat:
Console.WriteLine("Play again? (Y/N)");
string ans = Console.ReadLine();
switch (ans.ToUpper())
{
case "Y": goto again; break;
case "N": break; //continue
default: goto repeat; break;
}
}
You can use console.ReadKey() insted of using console.ReadLine().
console.ReadLine() wait for input set of character thats why you console window is apperre there after pressing any key.
You can use "do while" or "while" operator.If you dont want to use while(true) , you can use this diffirent way. I mean that when user enter 0 or -1 this system can stop. while()
bool repeat = true;
do
{
Console.WriteLine("Enter value ");
string typ = Console.ReadLine();
int num = int.Parse(typ);
if (num!=0)
// bla bla bla.
else
repeat = false;
}while (repeat);