错误:类型或命名空间定义,或预期的文件结束

时间:2015-12-01 14:46:22

标签: c#

我正在尝试制作一个程序来计算素数,但我得到这个错误“类型或名称空间定义,或预期的文件结束”

这是代码:

    namespace ConsoleApplication2
    {
        class Program
        {
            static void Main(string[] args)
            {
                public string PrimeNumbers(int n)
            {
                string result = n.ToString();
                try
                {
                    for (int i = 2; i < n; i++)
                    {
                        int rest = n % i;
                        if (rest == 0)
                        {
                            resultado = n + "isn't a prime number";
                            i = n + 1;
                        }
                        else
                        {
                            resultado = n + "it's a prime number";
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error checking prime number");
                    Console.WriteLine(e);
                }
                Console.WriteLine(result);
                Console.Read();
                return result;
            }
            }
        }
    }

来自Main的braket也给了我一个错误“} expect”,但是我添加或删除了brakets,错误仍然存​​在

1 个答案:

答案 0 :(得分:2)

你不能在另一个方法中声明方法,我相信它应该看起来像:

namespace ConsoleApplication2
{
    public class Program
    {
        public static void Main()
        {
                PrimeNumbers(100);
        }

        public static string PrimeNumbers(int n)
            {
                string result = n.ToString();
                try
                {
                    for (int i = 2; i < n; i++)
                    {
                        int rest = n % i;
                        if (rest == 0)
                        {
                            result = n + "isn't a prime number";
                            i = n + 1;
                        }
                        else
                        {
                            result = n + "it's a prime number";
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error checking prime number");
                    Console.WriteLine(e);
                }
                Console.WriteLine(result);
                return result;
            }
    }
}