Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Why am i getting an error in C#? Please check the code and email me!

+4 votes
asked May 6 by Костадин Клемов (320 points)
using System.IO;
using System;

class Program
{
    static void Main(string[] args)
    {
        int guess_count = 0;
        int guess_max = 3;
        string word = "kostadin";
        
        while (guess_count != guess_max)
        {
            Console.Write("Enter your guess: ");
            string guess_word = Console.ReadLine();
            
            if (guess_word == word)
            {
                Console.WriteLine("You win!");
                break;
            }
            guess_count++;
            
        }
        if (guess_word != word)
        {
            Console.WriteLine("You lose!");
        }
    }
}

1 Answer

+1 vote
answered May 7 by Peter Minarik (40,320 points)
edited May 11 by Peter Minarik

The scope of you variable guess_word was limited to within the while loop, hence outside of it in the if it is now known.

Your code fixed is below:

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        int guess_count = 0;
        int guess_max = 3;
        string word = "kostadin";
        string guess_word;
        
        while (guess_count != guess_max)
        {
            Console.Write("Enter your guess: ");
            guess_word = Console.ReadLine();
            
            if (guess_word == word)
            {
                Console.WriteLine("You win!");
                break;
            }
            guess_count++;
            
        }
        if (guess_word != word)
        {
            Console.WriteLine("You lose!");
        }
    }
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...