我的计算器无法使用c#console应用程序

时间:2015-09-20 13:02:26

标签: c# scope calculator

它可能是一个非常简单的解决方案,但当它提供3条错误消息时:

The name 'iNum1' does not exist in the current context  
The name 'iNum2' does not exist in the current context  
The name 'soOper' does not exist in the current context 

当我删除我的最后一行代码时,它可以工作但没有它我无法计算它。我希望有人能帮帮忙。这是代码。

//information
    Console.WriteLine("This is a calculator");

    //Let them fill in the first number
    Console.WriteLine("Please enter the first number");
    bool bNoNum1 = true;
    while (bNoNum1)
    {

        string sNum1 = Console.ReadLine();

        try
        {
            int iNum1 = int.Parse(sNum1);
            bNoNum1 = false;
        }

        catch (Exception)
        {
            Console.WriteLine("That's not a number");
        }

    }



    //Let them fill in (*, +, / of -)
    Console.WriteLine("Please enter +, +, - or :");

    bool bNoOperator = true;


    do
    {
        string sOper = Console.ReadLine();

        if (sOper == "x")
        {
            string soOper = "*";
            bNoOperator = false;
        }
        else if (sOper == ":")
        {
            string soOper = "/";
            bNoOperator = false;
        }
        else if (sOper == "+")
        {
            string soOper = "+";
            bNoOperator = false;
        }
        else if (sOper == "-")
        {
            string soOper = "-";
            bNoOperator = false;
        }
        else
        {
            Console.WriteLine("De operator " + sOper + " Is niet bekend. Kies uit +, -, x of :");
        }
    } while (bNoOperator);


    //Enter second number
    Console.WriteLine("Please enter the second number");

    bool bNoNum2 = true;
    while (bNoNum2)
    {
        string sNum2 = Console.ReadLine();

        try
        {
            int iNum2 = int.Parse(sNum2);
            bNoNum2 = false;
        }

        catch (Exception)
        {
            Console.WriteLine("That's not a number");
        }
    }

    //calculating

    int uitkomst = iNum1 + soOper + iNum2;

2 个答案:

答案 0 :(得分:2)

您需要将这3个变量声明为您的上下文之外的全局变量,将这些变量放在行的上方"像这样,

{{1}}

答案 1 :(得分:0)

您将iNum1和iNum2声明放在错误的位置 - 在一些内括号内。它们在最后一条生命线所在的范围内并不为人所知。将这些变量声明为不同的级别。

在任何情况下,当你这样做时,你会遇到另一个问题:soOper是一个字符串。您正在添加一个带字符串的int和另一个int。