So I haven't been coding for long so I'm not so experienced, I recently ran into a problem on replit.com where the console would print out:
error CS8803: Top-level statements must precede namespace and type declarations.
using System;
could anyone suggest the problem? Here is my code for anyone wondering:
int English;
int Science;
int AverageCalc;
AverageCalc = Convert.ToInt32(Console.ReadLine());
class Program {
public static void Main (string[] args) {
Console.WriteLine("Write your math grades");
Math = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Write your english grades");
English = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Write your science grades");
Science = Convert.ToInt32(Console.ReadLine());
AverageCalc = (Math+English+Science/3);
}
}
if (AverageCalc > 80)
{
Console.WriteLine("You passed with A mark!");
}
else if (AverageCalc < 80)
{
Console.WriteLine("You passed with B mark!");
}
else if (AverageCalc < 65)
{
Console.WriteLine("You passed with C mark!");
}
else if (AverageCalc < 60)
{
Console.WriteLine("You passed with D mark!");
}
else if (AverageCalc < 55)
{
Console.WriteLine("You got lower than D mark, try better next time.");
}
You're mixing top level statements and non-TLS. TLS essentially allows you to do away with all the
namespace/class/static mainand just write a C# program as if it were the contents of the Main method: learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/In essence, this means program structure is a bit wonky because you start with some TLS, then go more regular style, then back to TLS; switching away from a TLS structure (I would suggest you just get used to the namespace/class/main fluff; it's still heavily used, and to some extent it's a reasonable intro to curly braces and scope). It looks like:
A simple program like this is conducted entirely within the scope of the
Mainmethod's curly braces. Later, when you start getting into actual object oriented things and having more than one student whose grades you're tracking, you'll move stuff out of the static Main, and write inside other curly brace blocks, but this will do for now.You've forgotten to declare a variable for
math- I'll leave that as an exercise for you to sort out. Also, when variables are declared inside a method (Mainis a method) you should name them usingcamelCaserather thanPascalCase. It might not seem important now, but it's convention and following it helps later on when code gets more complex. PascalCase is typically used for public methods, properties, casses and namespaes, and camel for private or local.In short, your variables should be called
english,science, andaverageCalc