【问题标题】:"CS1513: } Expected" Error [closed]“CS1513:} 预期”错误 [关闭]
【发布时间】:2018-05-22 01:39:30
【问题描述】:

我在编译以下代码时不断收到“CS1513: } Expected”错误。错误发生在 user_input 方法的左括号处。

我是 C# 新手,仍在学习。抱歉,如果我遗漏了一些明显的东西。我已经搜索了多个论坛并没有找到解决方案。提前感谢您的帮助!

using System;
namespace App
{
class AppClass
{
    static void Main()
    {

    }
    void user_input()
    {
        public int input1;
        public int input2;
        public string operation;

        while (operation != "+" or operation != "-")
        {
            Console.WriteLine("Would you like to Add or Subtract?");
            operation = Convert.ToString(Console.ReadLine());
        }

        Console.WriteLine("Please enter the first input:");
        input1 = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Please enter the second input:");
        input2 = Convert.ToInt32(Console.ReadLine());
    }
    void do_math()
    {
        public int output;
        if (operation == "+")
        {
            output = input1+input2;
        } else {
            output = input1-input2;
        }
    }
    void display()
    {
        Console.WriteLine("The answer is {0}", output);
    }
}
}

【问题讨论】:

  • {} 不是问题所在。问题是将可访问性修饰符应用于局部变量,并在您的 while 中使用 or 而不是 ||
  • 另外,你实际上想要 && 而不是 or (||) 语句; opeartion 必须既不是 + 也不是-
  • 我猜错误信息是有道理的。 Visual Studio 已确定变量声明优先,因此它认为您必须在方法之外声明它们并指示您添加 } 以便将变量移出。
  • 谢谢大家!我在课后移动了变量并编译了它。将“或”更改为“||”。感谢您的快速响应并向我展示了正确的方式!

标签: c# error-handling compiler-errors


【解决方案1】:

您应该在方法之外声明所有公共变量,因为您在每个函数中都使用它们并且 VS 考虑这一点,它也不是 OR 它的 ||

using System;
namespace App
{
    class AppClass
    {
        public int input1;
        public int input2;
        public string operation;
        public int output;
        static void Main()
        {

        }
        void user_input()
        {
            while (operation != "+" || operation != "-")
            {
                Console.WriteLine("Would you like to Add or Subtract?");
                operation = Convert.ToString(Console.ReadLine());
            }

            Console.WriteLine("Please enter the first input:");
            input1 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Please enter the second input:");
            input2 = Convert.ToInt32(Console.ReadLine());
        }
        void do_math()
        {

            if (operation == "+")
            {
                output = input1 + input2;
            }
            else
            {
                output = input1 - input2;
            }
        }
        void display()
        {
            Console.WriteLine("The answer is {0}", output);
        }

    }

}

【讨论】:

  • 他还应该从方法声明中删除“public”关键字
  • 解释一下代码问题,比如错误或关键字,或者为什么需要在方法之外声明变量。我认为这是正确的答案,但如果您提供更多详细信息会很好。
  • @PedroFernandes 添加了详细信息
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-13
  • 2016-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多