Home > Back-end >  Why is this code resulting in an syntax error?
Why is this code resulting in an syntax error?

Time:03-30

I was coding using an online compiler, and I was testing some C# code. It was something I personally, have done before, and the compiler took it. But now when I run this code. It results in a syntax error, and my online compiler is being annoying and won't tell me what the error is.

using System;
using System.Threading.Tasks;
using static System.Console;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            public int hunger = 34;
            WriteLine($"Hunger level is {hunger}");
            System.Threading.Thread.Sleep(1000);
            Eat("meat");
        }
        static void Eat(string food)
        {
            if (food == "meat")
            {
                hunger = hunger - 15;
                WriteLine($"Hunger level in now {hunger}");
            }
            else
            {
                WriteLine("Not enough food...");
            }
        }
    }
}

Why is this resulting in an error, and what can I do about it?

EDIT: Solved: I was dumb and didn't notice that hunger was in Main. Plus, forgot about scope.

CodePudding user response:

Others already spotted the problems, so here's the working code with minimal changes to what you wrote.

public class Program
{
    static int hunger = 34;
    static void Main(string[] args)
    {
        Console.WriteLine("Hunger level is {0}", hunger);
        System.Threading.Thread.Sleep(1000);
        Eat("meat");
    }

    static void Eat(string food)
    {
        if (food == "meat")
        {
            hunger = hunger - 15;
            Console.WriteLine("Hunger level in now {0}", hunger);
        }
        else
        {
            Console.WriteLine("Not enough food...");
        }
    }
}

CodePudding user response:

You can't user access modifiers on variables in methods, because it makes no sense, they can only be seen inside those methods

public int hunger = 34;

CodePudding user response:

Here is working code, although got beaten to the line.. :)
Slightly nicer tho..

using static System.Console;

namespace Test;

class Program
{
    static int hunger = 0;

    static void Main(string[] args)
    {
        hunger = 34;
        WriteLine($"Hunger level is {hunger}");
        Task.Run(async () => await Eat("meat"));
        ReadKey();
    }

    async static Task Eat(string food)
    {
        await Task.Delay(1000);
        if (food == "meat") { hunger -= 15; WriteLine($"Hunger level in now {hunger}"); }
        else { WriteLine("Not enough food..."); }
    }
}

Edit: Replaced ReadLine by ReadKey()...

  • Related