Adding value to int variable each run of the loop - c#

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

Related

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

How can I get a message to appear only once if a random number doesn't equal one in a vector?

I am making a small lottery game. Everything works fine but I can't get the message I want to be displayed if the user doesn't guess the correct number to only appear once. I don't know how to get it to appear only once and I know why it appears multiple times.
static void Main(string[] args)
{
int[] userGuessNums = new int[10];
Console.WriteLine("Input 10 numbers between 1-50.");
for (int i = 0; i < userGuessNums.Length; i++)
{
try
{
Console.Write("Number " + (i + 1) + ": ");
string numbers = Console.ReadLine();
int userNumbers = Convert.ToInt32(numbers);
userGuessNums[i] = userNumbers;
}
catch
{
Console.WriteLine("Invalid input");
}
}
Console.Clear();
Random randomer = new Random();
int randomNumber = randomer.Next(1, 51);
Console.WriteLine("The numbers you have chosen:");
foreach (int element in userGuessNums)
{
Console.Write(element + " ");
}
Console.WriteLine();
Console.WriteLine("Press 'Enter' to see if you have won.");
Console.ReadLine();
Console.WriteLine("The winning number is: " + randomNumber);
for (int i = 0; i < userGuessNums.Length; i++)
{
if (userGuessNums[i] == randomNumber)
Console.WriteLine("Congratulations! You won!");
else if (userGuessNums[i] != randomNumber)
{
Console.WriteLine("Sorry, you lose.");
}
}
}
You can check to see if the random number is in the array input by the user.
Import Linq at the top of your code
using System.Linq;
And after Console.WriteLine("The winning number is: " + randomNumber); replace the for-loop with
if (userGuessNums.Contains(randomNumber))
{
Console.WriteLine("Congratulations! You won!");
}
else
{
Console.WriteLine("Sorry, you lose.");
}
Modify your last for loop like so. Loop through your array and find a winning number then set your win prompt outside the loop.
Why does this work? Let's break it down. Mainly I'm separating the prompt for the win from the loop; this is going to stop it from continually displaying, which is what you want. However, we still need to isolate the element within the array that is an acceptable condition. By setting our userWonNum outside of the for loop with a value of -1 (An impossible win condition), it protects from an accidental win. Then we loop through our array and find a winning number and assign it to that variable. Once the loop is completed, then it will move to the next block and check if we had one.
Exciting tip on this. If you loop through with more than one winning number, it will re-assign multiple times if you implement more than one winning number, but for now, it will work.
int userWonNumber = -1;
for (int i = 0; i < userGuessNums.Length; i++)
{
if (userGuessNums[i] == randomNumber)
{
userWonNumber = randomNumber;
}
}
if (userWonNumber == randomNumber)
{
Console.WriteLine("Congrats, you won!");
}
else
{
Console.WriteLine("Sorry you lost!");
}

C# How do I error check the input ensuring only integers between 1-100 are accepted

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
}

C# 'Unassigned local variable'?

I tried to make a piece of code which would roll a dice in the end to decide which character wins and it keeps on saying that there are errors (Use of unassigned local variable 'skillmodifier') & (Use of unassigned local variable 'strengthmodifier'). I would really appreciate any help. P.S I have only been doing programming for a short period of time on Visual Studio 2010. Please help me find a solution to this problem, the problem occurs because I use the variables 'strengthmodifier' and 'skillmodifier' twice. Thank you, yours faithfully, Vikash.
I will paste the task breif below and the code after that:
Task 3 Determining the outcome of an encounter
When there is an encounter between two characters the outcome is determined by the following
process:
• The differences between the strength attributes for the two characters is calculated
• This difference is divided by 5 and then rounded down to create a ‘strength modifier’
• The process is repeated for the skill attribute to create a ‘skill modifier’
• Each player throws a 6 sided dice.
• If the scores on both dice are the same, no changes are made
• If the scores are not the same, the player with the highest score adds the ‘strength
modifier’ to the strength value and the ‘skill modifier’ to the skill value for their
character
• The player with the lower score on the dice subtracts these modifiers from the
strength and skill values for their character
• If a skill value becomes negative, then it is stored as zero
• If a strength value becomes zero or negative, then the character dies.
The program should:
*• Allow the user to input the strength and skill for two characters.
• Display the outcome of the encounter using the process above.
Design an algorithm to describe this process. Write, test and evaluate the code.*
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Task3
{
class Program
{
static void loopfsto()
{
Console.WriteLine("Please enter a value of strength, and then press enter");
string csto = Console.ReadLine(); // Read string from console
int csto1;
if (int.TryParse(csto, out csto1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + csto1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfsto();
}
}
static void loopfsko()
{
Console.WriteLine("Please enter a value of skill, and then press enter");
string csko = Console.ReadLine(); // Read string from console
int csko1;
if (int.TryParse(csko, out csko1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + csko1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfsko();
}
Console.Clear();
}
static void loopfstt()
{
Console.WriteLine("Please enter a value of strength for, and then press enter");
string cstt = Console.ReadLine(); // Read string from console
int cstt1;
if (int.TryParse(cstt, out cstt1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + cstt1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfstt();
}
Console.Clear();
}
static void loopfskt()
{
Console.WriteLine("Please enter a value of skill for, and then press enter");
string cskt = Console.ReadLine(); // Read string from console
int cskt1;
if (int.TryParse(cskt, out cskt1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + cskt1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfskt();
}
}
static void Main(string[] args)
{
string Character1;
string Character2;
int strengthmodifiertoround;
int skillmodifiertoround;
int strengthmodifier;
int skillmodifier;
Console.Title = "Strength and Skill";
Console.WriteLine("Welcome to Strength and Skill, please press enter to continue.");
Console.ReadKey();
Console.Clear();
Console.WriteLine("Please enter a name for character 1, then press enter.");
Character1 = Console.ReadLine();
Console.Clear();
Console.WriteLine("Please enter a name for character 2, then press enter.");
Character2 = Console.ReadLine();
Console.Clear();
Console.WriteLine("Please enter a value of strength for " + Character1 + ", and then press enter");
string csto = Console.ReadLine(); // Read string from console
int csto1;
if (int.TryParse(csto, out csto1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + csto1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfsto();
}
Console.Clear();
Console.WriteLine("Please enter a value of skill for " + Character1 + ", and then press enter");
string csko = Console.ReadLine(); // Read string from console
int csko1;
if (int.TryParse(csko, out csko1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + csko1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfsko();
}
Console.Clear();
Console.WriteLine(Character1 + " has a strength of " + csto1 + " and a skill of " + csko1 + ".");
Console.ReadKey();
Console.Clear();
Console.WriteLine("Please enter a value of strength for " + Character2 + ", and then press enter");
string cstt = Console.ReadLine(); // Read string from console
int cstt1;
if (int.TryParse(cstt, out cstt1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + cstt1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfstt();
}
Console.Clear();
Console.WriteLine("Please enter a value of skill for " + Character2 + ", and then press enter");
string cskt = Console.ReadLine(); // Read string from console
int cskt1;
if (int.TryParse(cskt, out cskt1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + cskt1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfskt();
}
Console.Clear();
Console.WriteLine(Character2 + " has a strength of " + cstt1 + " and a skill of " + cskt1 + ".");
Console.ReadKey();
Console.Clear();
//--- Finds out if strength for character 1 is higher than 2 or vice versa. Then finds difference between two and makes a variable called strengthmodifier ---//
{
if (csto1 < cstt1)
{
strengthmodifiertoround = cstt1 - csto1;
strengthmodifier = strengthmodifiertoround / 5;
}
if (cstt1 < csto1)
{
strengthmodifiertoround = csto1 - cstt1;
strengthmodifier = strengthmodifiertoround / 5;
}
}
//--- Finds out if skill for character 1 is higher than 2 or vice versa. Then finds difference between two and makes a variable called skillmodifier ---//
{
if (csko1 < cskt1)
{
skillmodifiertoround = cskt1 - csko1;
skillmodifier = skillmodifiertoround / 5;
}
if (cskt1 < csko1)
{
skillmodifiertoround = csko1 - cskt1;
skillmodifier = skillmodifiertoround / 5;
}
}
//--- Tells user to put input and roll a virtual dice (which is actually creating a number between 1 and 6) ---//
Console.WriteLine(Character1 + ", please press enter to roll dice");
Console.ReadKey();
Random rand = new Random();
int character1RandomNumber = rand.Next(1, 6);
Console.WriteLine(Character2 + ", please press enter to roll dice");
Console.ReadKey();
Random rand1 = new Random();
int character2RandomNumber = rand1.Next(1, 6);
Console.WriteLine(Character1 + " rolled a " + character1RandomNumber + " and " + Character2 + " rolled a " + character2RandomNumber + ".");
Console.ReadKey();
if (character1RandomNumber < character2RandomNumber)
{
int char2st = cstt1 + strengthmodifier;
int char2sk = cskt1 + skillmodifier;
int char1st = csto1 - strengthmodifier;
int char1sk = csko1 - skillmodifier;
}
if (character2RandomNumber < character1RandomNumber)
{
}
int ch2st = cstt1 - strengthmodifier;
int ch2sk = cskt1 - skillmodifier;
int ch1st = csto1 + strengthmodifier;
int ch1sk = csko1 + skillmodifier;
}
}
}
Actually, i think your problem is because skillmodifier and strengthmodifier do not get assigned values on all code paths. ie. They are only assigned values from within if clauses and visual studio cannot determine whether or not they are assigned for all possible outcomes. This warning shouldn't stop your code compiling but if you want it to go away you can do something like
int skillmodifiertoround = 0;
instead of just
int skillmodifiertoround;
Now skillmodifiertoround is given a value on declaration.
Edit: "This warning shouldn't stop your code compiling" - Apparently it will stop the program from compiling correctly in c# but the same error in vb only gives a warning but still compiles.
Its rather simple really
int skillmodifier;
You need to assign it - that is give it a value, even a default one - before you can use it. Otherwise the program doesn't know what value it has.
So something like
int skillmodifier = -1;
will fix it for you.
When you declare int skillmodifier declare it as whatever the default value should be,e.g. int skillmodifier = 0;
Do the same for strengthmodifier and you should be good to go!
The problem is that the compiler can detect a way of executing your code without these parameters being set.
Local variables in C# must be initialized before they are used.
From MSDN
Also see related questio Why aren't unassigned local variables automatically initialized?
For generics where type is not known, use default keyword
I think the other people have given you the answer, but I spotted something else.
Instead of
//method
if(tryparse)
{
//done
}
else
//loop
you should turn the methods into methods that return ints and then...
int csko = loopCsko()

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