1

您好,感谢您查看我的帖子。一般是 C# 和 Oop 的新手。到目前为止学习一直很顺利,但是当我尝试创建(和调用)一个计算用户输入的数据的构造函数时遇到了问题。

如果可能:我想创建 3 个类。

显示信息并获取用户输入的 MainDisplay 类。

“仅”计算 bmi 的 BMIBlueprint 类。

计算 bfp 的 BFPBlueprint 类(需要使用 bmi total)。

我已经使用一个类完成了这项任务,但我真的很想知道/理解如何使用多个类来做到这一点。在提出这个问题之前,我已经看过/阅读/研究了过去两周我能找到的所有资源,但我无法理解创建一个进行计算的构造函数,然后在 main 中调用它以使用用户输入数据对于变量..

最底层的代码是我如何在一节课中完成的(但还没有完成)。不过,您可以无视所有这些,我只是不想表现得像我完全绝望或试图作弊一样。

这就是我到目前为止所拥有的。第一个是我创建的 BMIBlueprint 类,它只是用作基于用户输入的 bmi 计算器,我计划在我的 MainClass 中调用它。此外,这大约是我尝试使其工作的第 200 个不同版本,它可能与它可能/应该看起来的样子相去甚远......

class BMIBlueprint {

    public double bmiBefore;
    public double bmiAFter;

    public BMIBlueprint() { }

    public BMIBlueprint(double height, double weight) {

        bmiBefore = (height * height) * weight;
    }

    public BMIBlueprint(double bmiConst) {

        bmiAFter = bmiBefore * 703;

    }
}

如何“使用”上述类构造函数来计算用户在我的主类中输入的内容?还是我偏离了轨道?我的主类在我要求用户输入的位置下方,然后将这些值放在我的构造函数中。

static void Main() {

    Write("Enter weight: ");
    double weight = double.Parse(ReadLine());

    Write("Enter height: ");
    double height = double.Parse(ReadLine());

    BMIBlueprint calcBmi = new BMIBlueprint(newBmiOne, newBmiTwo);

    //then display after calculated
    WriteLine("The finished cal should be shown here: {0:N2}", calcBmi);

我已经尝试了很多不同的方法,但这就是我现在所处的位置;如果有人有时间或善意地用一些笔记发布代码应该是什么,以便我可以研究它,那绝对很棒,但也可能要求太多。如果没有任何帮助/建议/隐喻/类比将不胜感激。

下面的代码是我在一节课中完成的所有工作 - 几乎完成,但不是问题的一部分,应该被忽略。

static void Main() {

    EntranceBlueprint entrance = new EntranceBlueprint();

    WriteLine(entrance);

    BMIBlueprint bmiCalculator = new BMIBlueprint();

    Write("First, enter your weight in lbs: ");
    double newWeight = double.Parse(bmiCalculator.weight = ReadLine());

    Write("\nGreat, now enter your height in inches: ");
    double newHeight = double.Parse(bmiCalculator.height = ReadLine());

    bmiCalculator.bmiVar = 703;
    double totalBmi = ((newWeight * bmiCalculator.bmiVar) / 
                      (newHeight * newHeight));

    WriteLine("\nPerfect! Your bmi is: {0:N2}. With just a few more 
              inputs we'll have your bfp. ", +totalBmi);

    Write("\npress any key to continue");
        ReadKey();

    BFPBlueprint bfpCalculator = new BFPBlueprint();              

    Write("According to _ your bfp is more accurate because it takes     
    into account your age and gender. So enter your age first: ");

    double newAge = double.Parse(bfpCalculator.age = ReadLine());
    Write("\nGreat, now enter your sex, like this (male or female): ");

    string newSex = ReadLine();

        if (newAge >= 13 && newSex.ToLower() == "male") {
            double totalAdultMale = 
                (1.20 * totalBmi) - (0.23 * newAge) - (10.8 * 1) - 5.4;
                Write("\nYour bfp is: {0:N2} ", totalAdultMale);
                    if (totalAdultMale > 1 && totalAdultMale < 13)
                    Catagories(); }

        else if (newAge <= 12 && newSex.ToLower() == "male") {
            double totalYouthMaleBfp = 
            (1.51 * totalBmi) - (0.70 *newAge) - (3.6 * 1) + 1.4;
            Write("Perfect! Your bfp is: {0:N2}",

        else if (newAge >= 13 && newSex.ToLower() == "female") {
            double totalAdultFemaleBfp = 
            (1.20 * totalBmi) - (0.23 * newAge) - (10.8 * 0) - 5.4;
            Write("Perfect! Your bfp is: {0:N2} ",totalAdultFemaleBfp); }


        else if (newAge <= 12 && newSex.ToLower() == "female") {
            double totalYouthFemaleBfp = 
            (1.51 * totalBmi) - (0.70 * newAge) - (3.6 * 0) + 1.4;
            Write("Perfect! Your bfp is {0:N2} ", totalYouthFemaleBfp); }

        else { Write("\nYou must have typed something wrong, Try 
               again"); }

        ReadKey();
4

4 回答 4

1

您可以通过多种方式解决此问题,但从纯粹的 OOP 角度来看,使用类是一个好主意。

通过构造参数初始化类的成员,使用构造函数构建对象:

    public class BMIBlueprint {

    private const double BMI_CONST = 703;

    public double Height {get; private set;} 
    public double Weight {get; private set;}


    public BMIBlueprint(double height, double weight) {

        this.Height = height;
        this.Weight = weight;
    //instead of passing in variables to perform a function in your constructor
    //use them to initialize your member variables
    //bmiBefore = (height * height) * weight; 
    }

    public double GetBMIBefore(){

        double bmiBefore = (this.Height * this.Height) * this.Weight;
        return bmiBefore;
    }

    public double GetBMIAfter() {

        double bmiBefore = this.GetBMIBefore();
        double bmiAfter = bmiBefore * BMI_CONST;
        return bmiAfter;
    }

然后调用该类中包含的方法从对象中进行计算:

static void Main() {
    Write("Enter weight: ");
    double weight = double.Parse(ReadLine());

    Write("Enter height: ");
    double height = double.Parse(ReadLine());

    BFPBlueprint bmiCalculator = new BFPBlueprint(height, weight);

    double bmiBefore = bmiCalculator.GetBMIBefore();
    double bmiAfter = bmiCalculator.GetBMIAfter();
    //etc...

这里的重点是将所有 bmi 计算逻辑和值封装在一个类中,以便于使用。

或者

您可以改为使用实现这些方法且不包含任何成员变量的静态类:

public static class BmiCalculator
{
    private const double BMI_CONST = 703;

    public double static GetNewBMI(double height, double weight)
    {
        double newBMI = (height * height) * weight;
        return newBMI;
    }

    public double GetAdjustedBMI(double oldBMI) 
    {
        double adjustedBMI = oldBMI * BMI_CONST;
        return adjustedBMI;
    }

要在您的 Main 中实施:

static void Main() {
    Write("Enter weight: ");
    double weight = double.Parse(ReadLine());

    Write("Enter height: ");
    double height = double.Parse(ReadLine());

    double bmiBefore = BmiCalculator.GetNewBMI(height, weight);
    double bmiAfter = BmiCalculator.GetAdjustedBMI(bmiBefore);
    //etc...
于 2016-10-23T07:19:08.203 回答
0

这是一个更高级的 OOP 方法示例,包含输入验证。请注意,您可能需要根据您想要拥有的确切功能修改 Person。计算器/历史跟踪可能是对象本身。我只是展示了您发布的摘录如何以 C#/OOP 方式编写。

using System;
using System.Linq;

namespace BMI_StackOverflow
{
    class Program
    {
        static void Main(string[] args)
        {
            PersonValidator inputValidator = new PersonValidator();
            Person person = new Person();
            person.Weight = CollectUserInput<double>("First, enter your weight in lbs: ",
                inputValidator.IsValidWeight, "Please enter a positive number: ");
            person.Height = CollectUserInput<double>("\nGreat, now enter your height in inches: ",
                inputValidator.IsValidHeight, "Please enter a positive number: ");

            double bmi = person.GetBmi();
            Console.WriteLine("\nPerfect! Your bmi is: {0:N2}. With just a few more inputs we'll have your bfp. ", +bmi);
            Console.Write("\nPress any key to continue");
            Console.ReadKey();

            person.Age = CollectUserInput<int>("According to _ your bfp is more accurate because it takes into account your age and gender. So enter your age first: ",
                inputValidator.IsValidAge, "Please enter a positive, non-decimal number.");
            string sex = CollectUserInput<string>("\nGreat, now enter your sex, like this (male or female): ",
                inputValidator.IsValidSex, $"That sex is not recognized. Please input one of: {string.Join(", ", Enum.GetNames(typeof(Person.BiologicalSex)).Select(x => x.ToLower()))}");
            person.Sex = inputValidator.ParseSex(sex).Value;

            double bfp = person.GetBfp();
            Console.WriteLine("Perfect! Your bfp is {0:N2} ", +bfp);
            Console.ReadKey();
        }

        /// <summary>
        /// Prompts user for console input; reprompts untils correct type recieved. Returns input as specified type.
        /// </summary>
        /// <param name="message">Display message to prompt user for input.</param>
        private static T CollectUserInput<T>(string message = null)
        {
            if (message != null)
            {
                Console.WriteLine(message);
            }
            while (true)
            {
                string rawInput = Console.ReadLine();
                try
                {
                    return (T)Convert.ChangeType(rawInput, typeof(T));
                }
                catch
                {
                    Console.WriteLine($"Please input a response of type: {typeof(T).ToString()}");
                }
            }
        }

        /// <summary>
        /// Prompts user for console input; reprompts untils correct type recieved. Returns input as specified type.
        /// </summary>
        /// <param name="message">Display message to prompt user for input.</param>
        /// <param name="validate">Prompt user to reenter input until it passes this validation function.</param>
        /// <param name="validationFailureMessage">Message displayed to user after each validation failure.</param>
        private static T CollectUserInput<T>(string message, Func<T, bool> validate, string validationFailureMessage = null)
        {
            var input = CollectUserInput<T>(message);
            bool isValid = validate(input);
            while (!isValid)
            {
                Console.WriteLine(validationFailureMessage);
                input = CollectUserInput<T>();
                isValid = validate(input);
            }
            return input;
        }
    }

    public class Person
    {
        public double Weight { get; set; }
        public double Height { get; set; }
        public int Age { get; set; }
        public BiologicalSex Sex { get; set; }

        private const int bmiVar = 703;

        public double GetBmi()
        {
            return ((Weight * bmiVar) /
                   (Math.Pow(Height, 2)));
        }

        public double GetBfp()
        {
            double bmi = GetBmi();
            switch (Sex)
            {
                case BiologicalSex.MALE:
                    if (Age >= 13)
                    {
                        return (1.20 * bmi) - (0.23 * Age) - (10.8 * 1) - 5.4;
                    }
                    return (1.51 * bmi) - (0.70 * Age) - (3.6 * 1) + 1.4;
                case BiologicalSex.FEMALE:
                    if (Age >= 13)
                    {
                        return (1.20 * bmi) - (0.23 * Age) - (10.8 * 0) - 5.4;
                    }
                    return (1.51 * bmi) - (0.70 * Age) - (3.6 * 0) + 1.4;
                default:
                    throw new Exception($"No BFP calculation rule for sex: {Sex}");
            }
        }

        public enum BiologicalSex
        {
            MALE,
            FEMALE
        }
    }

    public class PersonValidator
    {
        public bool IsValidWeight(double weight)
        {
            return weight >= 0;
        }

        public bool IsValidHeight(double height)
        {
            return height >= 0;
        }

        public bool IsValidAge(int age)
        {
            return age >= 0;
        }

        public bool IsValidSex(string sex)
        {
            return ParseSex(sex) != null;
        }

        /// <summary>
        /// Attempts to parse sex from string. Returns null on failure.
        /// </summary>
        public Person.BiologicalSex? ParseSex(string sex)
        {
            int temp;
            bool isNumber = int.TryParse(sex, out temp);
            if (isNumber)
            {
                return null;
            }
            try
            {
                return (Person.BiologicalSex)Enum.Parse(typeof(Person.BiologicalSex), sex, ignoreCase: true);
            }
            catch (ArgumentException ex)
            {
                return null;
            }
        }
    }
}
于 2016-10-23T08:33:43.913 回答
0

这是一个简单的例子:

using System;

namespace ConsoleApplication
{
    class BMIBlueprint
    {
        private const int BMI_VAR = 703;

        public double Bmi { get; private set; }

        public BMIBlueprint(double height, double weight)
        {
            Bmi = height * height * weight;
        }

        public void Adjust()
        {
            Bmi *= BMI_VAR;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter weight: ");
            double weight = double.Parse(Console.ReadLine());

            Console.Write("Enter height: ");
            double height = double.Parse(Console.ReadLine());

            BMIBlueprint calcBmi = new BMIBlueprint(height, weight);

            calcBmi.Adjust();

            //then display after calculated
            Console.WriteLine("The finished cal should be shown here: {0:N2}", calcBmi.Bmi);

            Console.Write("\nPress any key...");
            Console.ReadKey();
        }
    }
}
于 2016-10-23T06:24:36.403 回答
0

你的问题是这段代码:

WriteLine("The finished cal should be shown here: {0:N2}", calcBmi);

WriteLine函数不会将calcBmi(即 a BMIBlueprint)作为参数。也是{0:N2}错误的语法。但是,您可以这样做:

WriteLine("The finished cal.bmiBefore should be shown here: {0}", calcBmi.bmiBefore);
WriteLine("The finished cal.bmiBefore should be shown here: {0}", calcBmi.bmiBefore);
于 2016-10-23T06:30:05.917 回答