Reputation: 47
I have written the code for the following program:
Inside the for loop block of code I need to perform the following logic:
I getting an error with this code. Can anybody help me?
int answer = 0, guess;
string input = "" ;
//Create an oject of the Random class
Random number = new Random();
answer = number.Next(1, 11);
answer = number.Next(1, 11);
Console.WriteLine("Select Randomly Number between 1 and 10 ");
// guess = (Convert.ToInt32(Console.ReadLine()));
for (int i = 1; i <=5; i++)
{
Console.Write("Enter Guess :");
guess = Convert.ToInt32(Console.ReadLine());
if (guess > answer)
{
Console.WriteLine("Guess is Higher");
}
else if (guess < answer)
{
Console.WriteLine("Guess is Lower");
}
else
{
Console.WriteLine("You Won !!\t {0} is the correct number", guess);
break;
i = 6;
}
}
Console.WriteLine("You Loose");
Console.WriteLine("The answer is {0} ", answer);
Console.ReadKey();
Upvotes: 0
Views: 5400
Reputation: 101681
Your code has many errors .I can't explain all of it, but here is the fixed version, still not perfect but it should do what you want:
int guess = 0, number;
//Create an object of the Random class
Random rnd = new Random();
number = rnd.Next(1, 11);
for (int i = 0; i < 6; i++)
{
Console.Write("Enter Guess :");
guess = Convert.ToInt32(Console.ReadLine());
if (guess > number)
{
Console.WriteLine("Higher, try again");
}
else if (guess < number)
{
Console.WriteLine("Lower, try again");
}
else
{
Console.WriteLine("You Won !!\t {0} is the correct number", guess);
i = 6;
}
if (i == 5)
{
Console.WriteLine("You Loose");
}
}
Console.ReadLine();
Update: Here is the list of your errors:
In below line input
is a string
, but you are trying to assign it to an integer
:
input = Convert.ToInt32(Console.ReadLine());
In this line, you are trying to overwrite input
, why ?
input = guess;
You are comparing i
with number
which is wrong because you should compare user's choice with random number and input is still a string,you can't compare an integer with a string directly.
In this line answer
is integer you are trying to concatenate it with a string
:
answer += (Console.ReadLine() + " ");
Probably there are some other errors but anyway,if you compare your code with the above code you will see solution of all these errors.
Upvotes: 1