2016-10-23 14 views
1

こんにちは、ありがとう、私のポストをチェックしてください。一般的にはC#とOopの新機能です。これまで滑らかな学習ができましたが、ユーザーが入力したデータを計算するコンストラクタを作成(および呼び出し)しようとすると、問題にぶつかります。C#を使用して入力を計算するクラスコンストラクタ

可能であれば:3つのクラスを作成したいと思います。

情報を表示し、ユーザー入力を取得するMainDisplayクラス。

bmiの計算を「行う」だけのBMIBlueprintクラス。

bfp(bmi totalを使用する必要がある)を計算するBFPBlueprintクラス。

私は1つのクラスを使用してこの作業を完了しましたが、複数のクラスを使用してこれを行う方法を実際に知りたい/理解したいと思います。私はこれをポーズする前に過去2週間に見つけたすべてのソースを見たり、読んだり、調べたりしましたが、計算を行うコンストラクタを作成してから、ユーザー入力データを使用するためにメインで呼び出すことはできませんでした変数のために。

非常に下のコードは私が1つのクラスでそれをやった方法です(しかし、かなり完成していません)。あなたはそれをすべて無視することができます、私は完全に絶望的であるか、またはチートしようとしているように外に出たくないだけです。

これはこれまで私が行ってきたことです。最初は私のBMIBlueprintクラスです。これは、メインクラスで呼び出す予定のユーザーからの入力に基づいて、bmiの電卓として使用するために作成したものです。私は上記のクラスのコンストラクタを「使用」するにはどうすればよい...

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; 

    } 
} 

それを動作させるためにしようとしているときにも、これは私の第200異なるバージョンについてですそしてそれは/実際のようになりますことができるものから非常に遠く、おそらくですユーザーがメインクラスで入力したものを計算しますか?または私はそれと一緒にトラックオフですか?私の主なクラスは、私がユーザーの入力を求めてから、それらの値をコンストラクタに配置する場所です。

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); 

私はこの多くのさまざまな方法を試しましたが、これは現在のところです。もし誰かが私はそれを勉強することができたので、絶対に素晴らしいだろうが、おそらくあまりにも多くを求めてコードが何をすべきか投稿する時間や親切を持っている。もしも助けや助言、隠喩、類推がないのであれば、大歓迎です。

以下のコードは、1つのクラスですべてを行ったところです。ほとんどの場合、問題の一部ではなく、無視する必要があります。

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(); 
+2

あなたは物事を計算するためにコンストラクタを使うべきではありません。 'BMIBlueprint'のコンストラクタは、高さと重さをとり、*これらの値を格納するだけです*。次に、身長と体重に基づいてBMIを返す 'GetBMI()'メソッドと、調整に基づいてBMIを返す2つ目のメソッドがあります。 – Rob

+0

これは役に立ちます。 [コンストラクタデザイン](https://msdn.microsoft.com/en-us/library/ms229060(v = vs.110).aspx) – shadow

+0

@Robと同意します。また、クラスインスタンスが構築されると、コンストラクタの* 1つだけが使用されます。例えば、BMIBlueprint bmiCalculator = new BMIBlueprint(); 'は引数のないコンストラクタを選択します。他の2つのコンストラクタは実行されません。 –

答えて

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(); 
     } 
    } 
} 
+0

素晴らしい!どうもありがとう。 – Dany

0

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

WriteLine関数は、パラメータとして、BMIBlueprintである、calcBmiになりません。また、{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); 
+0

私はあなたが何を意味するかを見ます。ありがとう。 – Dany

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; 
    } 

次にオブジェクトからあなたの計算(複数可)を行うには、このクラスに含まれるメソッド(複数可)を呼び出します:使いやすいようが一つのクラスにすべてのあなたのBMIの計算ロジックと値をカプセル化するためにここに

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... 

点です。

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; 
    } 

自分のメインに実装するには:

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... 
+0

パーフェクト!時々、私は頭の中の空白の部分を見て記入するだけの正確なものが必要です。私はいつも他の言語で教えてきましたが、C#は私の最初のものです。問題を見つけずにそれを見つめない限り、実際に何が正しいかを覚えておくより多くのダメージを感じます。 – Dany

+0

私はプログラミングが数学に似ていると感じます。コンセプトに取り組むときに時には「ああ」の瞬間があることがあります。私は、独学で学習することがあなたの快適ゾーンの外で実験して行くことであると言います。あなたは正しい方向に向かっています。既に同じ問題に取り組んでいる他の人からのフィードバックを得ることは、あなたをスピードアップします。また、C# –

0

がここにあります

OR

あなたは代わりにこれらのメソッドを実装し、任意のメンバ変数が含まれていない静的クラスを使用することができます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; 
      } 
     } 
    } 
} 
+0

の詳細については、[Microsoft Virtual Academy](https://mva.microsoft.com/)のMicrosoftの素晴らしい無料オンラインコースもあります。これは素晴らしいことです。私はこれを転記している間に変更するスイッチケースに取り組んでいましたが、それ以上の単純化された方法を思いつきました。 PersinalValidatorの – Dany

+0

でそれを分けてくれてありがとう。本当に文脈でそれを置くことができます。 – Dany

関連する問題