Number guessing game: Different message when guess = >100? - c#

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.

Related

User rolls two die and the application tells their luck depending on how quickly they got same numbers on both

When I run this Application. After I get both the same numbers, I don't get the message "Better luck next time". Can you please tell me what is wrong?
using System;
namespace FirstCode
{
class Program
{
static void Main(string[] args)
{
Random numberGen1 = new Random();
Random numberGen2 = new Random();
int roll1 = 5;
int roll2 = 0;
int count = 0;
Console.WriteLine("This is the LUCK indicator \n Press ENTER to roll die and TEST LUCK.");
while (roll1 != roll2)
{
Console.ReadKey();
roll1=numberGen1.Next(1,7);
roll2=numberGen2.Next(1,7);
Console.WriteLine("Roll 1-- " + roll1);
Console.WriteLine("Roll 2-- " + roll2);
count++;
}
Console.WriteLine("It took you " + count + " attempts to roll same number on both die.");
count = 9;
Convert.ToInt32(count);
if(count == 1){
Console.WriteLine("You are extremely lucky");
}
else if (count == 2){
Console.WriteLine("You are LUCKY today");
}
else if(count >= 3){
if(count <= 5){
Console.WriteLine("Your LUCK is average");
}
}
else {
Console.WriteLine("Better LUCK next time");
}
Console.ReadKey();
}
}
}
You are messing up the if/else statements. If you want to make it clearer (a bit, at least), maybe you can use a function, that will return the correct message depending on the count :
private string GetMessageFromCount(int count)
{
if (count <= 0)
throw new ArgumentException("Count cannot be 0 or negative", "count");
if (count == 1)
return "You are extremely lucky";
if (count == 2)
return "You are LUCKY today";
if (count <= 5) //we are obviously between 3 and 5 attempts
return "Your LUCK is average";
return "Better LUCK next time";
}
Then, to signal how lucky people are, just call the method :
Console.Writeline(GetMessageFromCount(count));

console application where the user has 5 tries to guess number between 1 and 100

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

cannot figure out while random number generator game is not working c#

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");
}
}

Check the length of integer variable

Is there a way to check a lenth of integer variable, and if is to long just trim it.
I hava a field in database that accepts 3 character, lenth is 3.
So is it possible to do like it's done with string variable
example:
cust_ref = cust_ref.Length > 20 ? cust_ref.Substring(0, 19) : cust_ref;
Thanks!
The easiest answer would be:
//The length would be 3 chars.
public int myint = 111;
myint.ToString().Length;
The following worked a treat for me!
public static int IntLength(int i)
{
if (i < 0)
throw new ArgumentOutOfRangeException();
if (i == 0)
return 1;
return (int)Math.Floor(Math.Log10(i)) + 1;
}
Original Source: http://www.java2s.com/Code/CSharp/Data-Types/Getthedigitlengthofanintvalue.htm
You don't have to convert it to a string to make it shorter, that can be done numerically:
if (num > 999) {
num %= 1000;
}
This will cut of digits from the left, if you want to cut them off from the right:
while (num > 999) {
num /= 10;
}
If the value can be negative, also check:
if (num < -99) {
num = -(-num % 100);
}
or:
while (num < -99) {
num = -(-num / 10);
}
cust_ref = cust_ref.ToString().Length > 20 ? Convert.ToInt32(cust_ref.ToString().Substring(0, 19)) : cust_ref;
or simply use
cust_ref = Convert.ToInt32(Convert.ToString(cust_ref).Substring(0, 19));
Use like this
cust_ref= cust_ref.Tostring().Length > 20 ? Convert.ToInt32(cust_ref.ToString().Substring(0, 19)) : cust_ref;
Nont very clear what you're asking for, but as much as I unerstood you're asking for:
int a = 1234567890;
for some reason you want to make it shorter, like
int b = MakeShorter(a);
//b == 1234 (say)
If so, the easiest solution may be, convert it to string, made what you already implemented and reconvert it back to int.
If this is not what you're asking for, please clarify.
The conversion to the string is ugly way to implement it.
It's require a pure math solution
int CutTheNumber(int number, int maxLen)
{
var maxSize = (int)Math.Pow(10, maxlen);
if(maxSize <= Math.Abs(number))
{
number %= maxSize;
}
return number;
}
Checking length
length = cust_ref.ToString().Length;
Remove extra bits
if (length > need)
{
cust_ref =Convert.ToInt32( cust_ref.ToString().Remove(length -(length- need)));
}
for this u will have to do some simple stuffs.
like
cust_ref = Convert.ToInt32(Convert.ToString(cust_ref).Substring(0, 19));
or u can manually store it in any variable and the
You can try this code. use if else statement to check the validation ..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace avaragescore
{
class Program
{
static void Main(string[] args)
{
float quiz;
float midterm;
float final;
float avrg=0;
Start:
Console.WriteLine("Please enter the Quize Score here");
quiz = float.Parse(Console.ReadLine());
if(quiz > 100)
{
Console.WriteLine("You have entered wrong score please re-enter");
goto Start;
}
Start1:
Console.WriteLine("Please enter the Midterm Score here");
midterm = float.Parse(Console.ReadLine());
if(midterm > 100)
{
Console.WriteLine("You have entered wrong score please re- enter");
goto Start1;
}
Start3:
Console.WriteLine("Please enter the Final Score here");
final = float.Parse(Console.ReadLine());
if(final > 100)
{
Console.WriteLine("You have entered wrong Score Please re-enter");
goto Start3;
}
avrg = (quiz + midterm + final) / 3;
if(avrg >= 90)
{
Console.WriteLine("Your Score is {0} , You got A grade",avrg);
}
else if (avrg >= 70 && avrg < 90)
{
Console.WriteLine("Your Score is {0} , You got B grade", avrg);
}
else if (avrg >= 50 && avrg < 70)
{
Console.WriteLine("Your Score is {0} , You got C grade", avrg);
}
else if (avrg < 50)
{
Console.WriteLine("Yor Score is {0} , You are fail", avrg);
}
else
{
Console.WriteLine("You enter invalid Score");
}
Console.ReadLine();
}
}
}

random number guessing game

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}");
}
}
}

Categories