在if语句中使用未分配的局部变量

时间:2019-09-15 18:34:54

标签: c#

所以我试图重新开始编码(以前在大学一年级,打算回去,但是需要重新开始。做这个简单的控制台应用程序并得到这个错误。

使用未分配的局部变量

我尝试在不同部分将卡路里设置为null,0、200等 代码,但似乎无济于事。

    static void Main(string[] args)
    {
        Console.WriteLine("Gender: Male(M)/Female(F)?");
        string gender = Console.ReadLine().ToLower();
        Console.WriteLine("Age?");
        int age = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Height?");
        int height = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Weight in KG?");
        int weightKG = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("How active are you?(Choose by inserting the number)");
        Console.WriteLine("1.No exercise");
        Console.WriteLine("2.Little to no exercise");
        Console.WriteLine("3.Light exercise(1-3 days a week)");
        Console.WriteLine("4.Moderate exercise(3-5 days a week");
        Console.WriteLine("5.Heavy exercise(6-7days a week)");
        Console.WriteLine("6.Very heavy exercise(Twice per day, extra heavy workouts");
        int activityLevel = Convert.ToInt32(Console.ReadLine());

        if (gender == "m")
        {
            int calories = Convert.ToInt32(66.4730 + (13.7516 * weightKG) + (5.0033 * height) - (6.7550 * age));
           // Console.WriteLine("Your daily calories are: {0}kcal",calories);
        }
        else if (gender == "f")
        {
            int calories = Convert.ToInt32(655.0955 + (9.5634 * weightKG) + (1.8496 * height) - (4.6756 * age));
           // Console.WriteLine("Your daily calories are: {0} kcal", calories);
        }
        else
        {
            Console.WriteLine("Please choose correct gender Male(M) or Female(F).");
        }

        if (activityLevel == 0)
        {
            int calories = Convert.ToInt32(calories * 1);
            Console.WriteLine("Your daily calories are: {0} kcal", calories);
        }
        else if (activityLevel == 1)
        {
            int calories = Convert.ToInt32(calories * 1.2);
            Console.WriteLine("Your daily calories are: {0} kcal", calories);
        }
        else if (activityLevel == 2)
        {
            int calories = Convert.ToInt32(calories * 1.375);
            Console.WriteLine("Your daily calories are: {0} kcal", calories);
        }
        else if (activityLevel == 3)
        {
            int calories = Convert.ToInt32(calories * 1.55);
            Console.WriteLine("Your daily calories are: {0} kcal", calories);
        }
        else if (activityLevel == 4)
        {
            int calories = Convert.ToInt32(calories * 1.725);
            Console.WriteLine("Your daily calories are: {0} kcal", calories);
        }
        else if (activityLevel == 5)
        {
            int calories = Convert.ToInt32(calories * 1.9);
            Console.WriteLine("Your daily calories are: {0} kcal", calories);
        }
        else
        {
            Console.WriteLine("Please choose a number between 0 and 5");
        }


    }
}

}

3 个答案:

答案 0 :(得分:0)

您要声明一个变量,然后在计算中使用它。

int calories = Convert.ToInt32(calories * 1);

这实际上与0 * n相同;

该变量应保存一个值,然后将其声明移动到此行下方:

int activityLevel = Convert.ToInt32(Console.ReadLine());

所以... int calories = 0;

static void Main(string[] args)
{
    Console.WriteLine("Gender: Male(M)/Female(F)?");
    string gender = Console.ReadLine().ToLower();
    Console.WriteLine("Age?");
    int age = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("Height?");
    int height = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("Weight in KG?");
    int weightKG = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("How active are you?(Choose by inserting the number)");
    Console.WriteLine("1.No exercise");
    Console.WriteLine("2.Little to no exercise");
    Console.WriteLine("3.Light exercise(1-3 days a week)");
    Console.WriteLine("4.Moderate exercise(3-5 days a week");
    Console.WriteLine("5.Heavy exercise(6-7days a week)");
    Console.WriteLine("6.Very heavy exercise(Twice per day, extra heavy workouts");
    int activityLevel = Convert.ToInt32(Console.ReadLine());
    int calories = 0;

    if (gender == "m")
    {
        calories = Convert.ToInt32(66.4730 + (13.7516 * weightKG) + (5.0033 * height) - (6.7550 * age));
        // Console.WriteLine("Your daily calories are: {0}kcal",calories);
    }
    else if (gender == "f")
    {
        calories = Convert.ToInt32(655.0955 + (9.5634 * weightKG) + (1.8496 * height) - (4.6756 * age));
        // Console.WriteLine("Your daily calories are: {0} kcal", calories);
    }
    else
    {
        Console.WriteLine("Please choose correct gender Male(M) or Female(F).");
    }

    if (activityLevel == 0)
    {
        calories = Convert.ToInt32(calories * 1);
        Console.WriteLine("Your daily calories are: {0} kcal", calories);
    }
    else if (activityLevel == 1)
    {
        calories = Convert.ToInt32(calories * 1.2);
        Console.WriteLine("Your daily calories are: {0} kcal", calories);
    }
    else if (activityLevel == 2)
    {
        calories = Convert.ToInt32(calories * 1.375);
        Console.WriteLine("Your daily calories are: {0} kcal", calories);
    }
    else if (activityLevel == 3)
    {
        calories = Convert.ToInt32(calories * 1.55);
        Console.WriteLine("Your daily calories are: {0} kcal", calories);
    }
    else if (activityLevel == 4)
    {
        calories = Convert.ToInt32(calories * 1.725);
        Console.WriteLine("Your daily calories are: {0} kcal", calories);
    }
    else if (activityLevel == 5)
    {
        calories = Convert.ToInt32(calories * 1.9);
        Console.WriteLine("Your daily calories are: {0} kcal", calories);
    }
    else
    {
        Console.WriteLine("Please choose a number between 0 and 5");
    }
}

答案 1 :(得分:0)

发生这种情况是因为您实际上是在每个块中创建新的int变量。当您定义变量并为其赋值时,该变量及其值仅在当前上下文中“存在”-为简单起见,请将该上下文视为直接父{}大括号之间的所有内容。因此,当您定义

if (gender == "m")
{
   int calories = Convert.ToInt32(66.4730 + (13.7516 * weightKG) + (5.0033 * height) - (6.7550 * age));
   // Console.WriteLine("Your daily calories are: {0}kcal",calories);
}

卡路里变量仅在if语句{}括号内可见。 如此简单的解决方法是在{}之外声明卡路里变量。

int baseCalories = 0;
if (gender == "m")
{
   baseCalories = Convert.ToInt32(66.4730 + (13.7516 * weightKG) + (5.0033 * height) - (6.7550 * age));
   // Console.WriteLine("Your daily calories are: {0}kcal",calories);
}
else if (gender == "f")
{
   baseCalories = Convert.ToInt32(655.0955 + (9.5634 * weightKG) + (1.8496 * height) - (4.6756 * age));
   // Console.WriteLine("Your daily calories are: {0} kcal", calories);
}
else
{
   Console.WriteLine("Please choose correct gender Male(M) or Female(F).");
}

,然后在其他if语句中使用此baseCalories变量。 要了解有关变量范围的更多信息,请阅读例如this

答案 2 :(得分:0)

关于您的问题(关于错误)。基本上,变量在声明它的块内可见。如果在if块内声明该变量,则仅在该if块内可见。如果在class块中声明它,则在该类及其方法内部,以及在使用正确的访问修饰符的情况下,在其他类中也将可见。

因此,如果需要访问变量,则需要根据其用法选择在何处声明它。

但是,这不是您遇到的唯一问题。您正在接受用户输入并直接使用它。这不是最佳实践。您需要先验证值,然后再使用它们。否则,您将要处理很多将在代码的每个点上引发的异常,并且应用程序越大,它将变得越糟。

以下几点将帮助您改善代码:

在使用前验证用户输入,这意味着您将用户输入存储在临时变量中,然后将其传递到验证逻辑中(如果通过了验证过程),然后将其值分配给原始变量。

为您的应用程序建模。 C#是面向对象的编程语言。构建更易于阅读,维护和扩展的代码结构更加容易。例如,如果您的应用程序依赖于某些值(例如性别,年龄,身高,体重),为什么不创建一个将存储这些值的模型,然后可以在代码中来回传递该模型。

public class PersonInfo
{
    public string Gender { get; set; }

    public int Age { get; set; }

    public int Height { get; set; }

    public int Weight { get; set; }

    public int ActivityLevel { get; set; }

    public double Calories { get; set; }

}

有了这个,您将始终在代码中使用该模型,并且您将知道值存储在该模型内部,这可以使您的工作更加轻松。

使用Enum 枚举是有原因的。使用它会很有用。在您的情况下,您可以将其用于这样的输入类型:

public enum InputType { Age, Height, Weight, ActivityLevel }

不转换源值 您需要保持原样。如果需要显示不同类型的值,例如从小数到整数。您可以在运行时转换它们,但不要触碰源代码。这是因为您可能需要在代码中的其他地方重用源值。因此,如果您转换源代码,就会搞砸了。

使用适当的方法,有时,您会遇到需要使用实例循环的地步,但是由于某些原因,您只是跳过了这一需求。这可能会导致代码逻辑中的一些错误和问题。例如,您的应用程序需要年龄,身高,体重和活动水平才能计算卡路里。如果缺少其中之一,则公式错误,并且公式错误。如果仅一次获得该值,并且如果无效则从不返回,则根本没有理由使用该公式,因为这些值是错误的。因此,为此,您需要确保在运行公式之前先获得每个变量。您可以创建一个循环并跟踪用户输入,如果无效,则强制用户输入有效值。或者直接退出应用程序。

代码重用 即使您知道它不会在其他任何地方重复使用,也应始终以重复使用同一代码为目的进行编码。这意味着,您将使用部分代码并将其放置在易于重用和维护的位置。例如性别,您可以将其放入方法中并重新调用它。卡路里公式也可以用作方法,等等。

最后,我整理了这些要点的样本,以给出更多的直观想法,希望对您有所帮助。

// Person Information Model
public class PersonInfo
{
    public string Gender { get; set; }

    public int Age { get; set; }

    public int Height { get; set; }

    public int Weight { get; set; }

    public int ActivityLevel { get; set; }

    public double Calories { get; set; }

}
class Program
{
    private static PersonInfo info = new PersonInfo();

    public enum InputType { Age, Height, Weight, ActivityLevel }


    static void Main(string[] args)
    {

        // default is null, to tell the application is invalid input
        string _gender = null;

        // keep the user inside this loop as long as the input is invalid.
        while (_gender == null)
        {
            Console.WriteLine("Gender: Male(M)/Female(F)?");
            _gender = GetGender(Console.ReadLine());

            if (_gender == null)
                Console.WriteLine("Gender has not been specified correctly. Please retype it.");
        }

        // it'll not go out of the loop until the user input is correct.
        info.Gender = _gender;

        // Create an array of inputs that you'll take from the user. 
        InputType[] inputs = { InputType.Age, InputType.Height, InputType.Weight, InputType.ActivityLevel };


        bool hasError = false;
        // Loop over the required inputs, and don't go to the next one until the user input a correct value.
        for (int x = 0; x < inputs.Length; x++)
        {
            double userinput;

            if (hasError)
                x--;

            if (inputs[x] != InputType.ActivityLevel)
            {
                Console.WriteLine("{0}? {1} ", inputs[x].ToString(), x);
                userinput = GetInt(Console.ReadLine(), inputs[x]);
            }
            else
            {
                Console.WriteLine("How active are you?(Choose by inserting the number)");
                Console.WriteLine("1.No exercise");
                Console.WriteLine("2.Little to no exercise");
                Console.WriteLine("3.Light exercise(1-3 days a week)");
                Console.WriteLine("4.Moderate exercise(3-5 days a week");
                Console.WriteLine("5.Heavy exercise(6-7days a week)");
                // Console.WriteLine("6.Very heavy exercise(Twice per day, extra heavy workouts");

                userinput = GetInt(Console.ReadLine(), InputType.ActivityLevel);

                if (userinput >= 0 && userinput < 6)
                {
                    info.ActivityLevel = (int)userinput;
                    info.Calories = GetCalories(info.Gender, info.Weight, info.Height, info.Age, info.ActivityLevel);
                }
                else
                {
                    //reset input 
                    userinput = -1;
                    Console.WriteLine("Please choose a number between 0 and 5");
                }


            }

            if (userinput != -1)
            {
                SetValues((int)userinput, inputs[x]);
                hasError = false;
            }
            else
            {
                Console.WriteLine("{0} has not been specified correctly. Please retype it.", inputs[x].ToString());
                hasError = true;
            }
        }


        // Now, you can show the user info with the calories as well. 

        Console.WriteLine("Your Gender\t\t:\t{0}", info.Gender);
        Console.WriteLine("Your Age\t\t:\t{0}", info.Age);
        Console.WriteLine("Your Height\t\t:\t{0}", info.Height);
        Console.WriteLine("Your Weight\t\t:\t{0}", info.Weight);
        Console.WriteLine("Your Activity Level\t:\t{0}", info.ActivityLevel);
        Console.WriteLine("Your daily calories\t:\t{0} kcal", Math.Round(info.Calories));


        Console.ReadLine();

    }


    public static string GetGender(string input)
    {
        if (!string.IsNullOrEmpty(input))
        {
            switch (input.ToLower())
            {
                case "m":
                case "male":
                    return "m";
                case "f":
                case "female":
                    return "f";
                default:
                    return null;
            }
        }
        else
        {
            return null;
        }

    }

    public static double GetActivityLevel(int level)
    {
        switch (level)
        {
            case 0:
                return 1;
            case 1:
                return 1.2;
            case 2:
                return 1.375;
            case 3:
                return 1.55;
            case 4:
                return 1.725;
            case 5:
                return 1.9;
            default:
                return -1;
        }

    }

    public static int GetInt(string input, InputType type)
    {
        if (!string.IsNullOrEmpty(input))
        {
            if (int.TryParse(input, out int result))
            {
                return result;
            }
            else
            {
                return -1;
            }
        }
        else
        {
            Console.WriteLine(type.ToString() + " is empty");
            return -1;
        }
    }


    public static void SetValues(int input, InputType type)
    {
        switch (type)
        {
            case InputType.Age:
                info.Age = input;
                break;
            case InputType.Weight:
                info.Weight = input;
                break;
            case InputType.Height:
                info.Height = input;
                break;
        }
    }

    public static double GetCalories(string gender, int weight, int height, int age, int activityLevel)
    {

        if (string.IsNullOrEmpty(gender))
        {
            Console.WriteLine("Gender has not been specified");
            return -1;
        }
        else
        {
            double _cal;

            var _level = GetActivityLevel(activityLevel);

            if (gender == "m")
                _cal = (66.4730 + (13.7516 * weight) + (5.0033 * height) - (6.7550 * age));
            else
                _cal = (655.0955 + (9.5634 * weight) + (1.8496 * height) - (4.6756 * age));

            //check first Activity Level, if is it -1 then it's invalid input, those it'll return it.
            return _level != -1 ? _cal * _level : -1;

        }

    }