Incrementing the Speed with Every Button Click - c#

I have a working application that compiles and everything. The two buttons work, however I need them to add/decrease 5 from the speed with every single click and currently they will only let me click once and accelerate gives me an answer of 5 for speed, while decelerate gives -5. How can I change this to allow for each button to be clicked and the speed update more than once?
Here is the form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Car_Class_BBrantley
{
public partial class Form1 : Form
{
private Car myCar;
public Form1()
{
myCar = new Car();
InitializeComponent();
}
private void GetCarData()
{
try {
myCar.Make = txtMake.Text;
myCar.Year = int.Parse(txtModel.Text);
myCar.Speed = 0;
}
catch (Exception ex)
{
MessageBox.Show(string.Concat("Must enter a valid make and year model for the car. ", ex.Message, "\r\n", ex.StackTrace));
}
}
private void btnAcc_Click(object sender, EventArgs e)
{
GetCarData();
myCar.AccSpeed(5);
lblAnswer.Text = " Your car is a " + myCar.Year + " " + myCar.Make + " and it is traveling " + myCar.Speed + " mph. ";
}
private void btnBrake_Click(object sender, EventArgs e)
{
GetCarData();
myCar.DecSpeed(5);
lblAnswer.Text = " Your car is a " + myCar.Year + " " + myCar.Make + " and it is traveling " + myCar.Speed + " mph. ";
}
}
}
Here is the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Car_Class_BBrantley
{
class Car
{
private int year;
private string make;
private int speed;
public Car()
{
this.year = 1994;
this.make = "Ford";
this.speed = 0;
}
public Car(string make, int year, int speed)
{
this.year = year;
this.make = make;
this.speed = speed;
}
public string Make
{
get { return make; }
set { make = value; }
}
public int Year
{
get { return year; }
set { year = value; }
}
public int Speed
{
get { return speed; }
set { speed = value; }
}
public void AccSpeed(int speedIncrement)
{
//Add check for speed limit ranges
Speed += speedIncrement;
}
public void DecSpeed(int speedDecrement)
{
//Add check for speed limit ranges
Speed -= speedDecrement;
}
}
}

Since this is probably homework I'll just give hints. With both click functions, the first call you make is to GetCarData(). Inside GetCarData(), you're calling myCar.Speed = 0;, so it's not surprising that you're going back to square one with each click.
Assuming that you want only one instance of Car for your entire application, you just need to modify the insides of GetCarData() to do (or not do) what you want. Just a few tweaks in that function, which I'll let you experiment with, and you'll be good to go.
However, if you want multiple Car objects in your app, you're going to need to modify it to have some kind of List (or better yet, an IDictionary).

Related

How can i change type of received data?

There is my client code in Unity:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using SignalR.Client._20.Hubs;
using SignalR.Client._20.Transports;
using Newtonsoft.Json.Linq;
public class SignalRHelper : MonoBehaviour {
public string signalRUrl = "http://localhost:52527";
public Text text;
public InputField message;
public GameObject testObj;
private string _resault;
private HubConnection _hubConnection = null;
private IHubProxy _hubProxy;
private IEnumerator Start()
{
Debug.Log("start()");
yield return new WaitForSeconds(1);
Debug.Log("start() 1 second");
StartSignalR();
}
void StartSignalR()
{
Debug.Log("StartSignalR");
if (_hubConnection == null)
{
_hubConnection = new HubConnection(signalRUrl);
Debug.Log(signalRUrl);
_hubConnection.Error += HubConnection_Error;
_hubProxy = _hubConnection.CreateProxy("ChatHub");
Subscription subscription = _hubProxy.Subscribe("synx");
subscription.Data += ChangePosition;
subscription = _hubProxy.Subscribe("broadcastMessage");
subscription.Data += Chat;
Debug.Log("_hubConnection.Start();");
_hubConnection.Start();
}
else
{
Debug.Log("Singnal already connected...");
}
//Пришёл ответ с сервера (got answer from server)
}
private void ChangePosition(object[] obj)
{
Debug.Log("Prishlo");
Debug.Log(obj[0] + "," + obj[1] + "," + obj[2]);
}
private void Chat(object[] obj)
{
Debug.Log(obj[1].ToString());
_resault += obj[0] + ":" + obj[1] + System.Environment.NewLine;
}
//
// Попробовать изменить на потоки
//
//
private void Update()
{
text.text = _resault;
if (Input.GetKeyUp(KeyCode.E))
{
Debug.Log("hubProxy of cube: " + _hubProxy);
_hubProxy.Invoke("Synx", testObj.transform.position.x, testObj.transform.position.y, testObj.transform.position.z);
}
}
private void HubConnection_Error(System.Exception obj)
{
Debug.Log("Hub Error = " + obj.Message +System.Environment.NewLine + obj.InnerException +
System.Environment.NewLine + obj.Data +
System.Environment.NewLine + obj.StackTrace +
System.Environment.NewLine + obj.TargetSite);
}
private void HubConnection_Closed()
{
Debug.Log("hubConnection_Closed()");
}
public void SendMessage()
{
_hubProxy.Invoke("Send", "UnityEpta", message.text);
}
//Если вышли с приложения нужно остановить Connection
private void OnApplicationQuit()
{
Debug.Log("OnApplicationQuit " + Time.time + "seconds");
_hubConnection.Error -= HubConnection_Error;
_hubConnection.
And it is in server:
using System;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace SignalRChat
{
public class ChatHub : Hub
{
public void Send(string name, string message)
{
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(name, message);
}
public void Synx(Stock stock)
{
Clients.All.synx(stock);
}
}
public class Stock
{
public float x { get; set; }
public float y { get; set; }
public float z { get; set; }
}
}
I receive position of testObj in 'object' type, but i can't change position with 'object' type. I tried to change from 'object' to 'float', but nothing heppened.
Then i replaced 'private void ChangePosition(object[] obj)' to 'private void ChangePosition(float[] obj)', i got error, that there is can be only 'object' type.Method 'Convert.ChangeType' doesn't work. How can i change receive data to float or how can i change position of testObj
in another ways?
The method signature must match!
(Means name of method and also number and type of parameters)
public void Synx(Stock stock)
matches not with :
_hubProxy.Invoke("Synx", testObj.transform.position.x, testObj.transform.position.y, testObj.transform.position.z);
Why you do not add to another libray like mycontracts and reference it in your client and your server project.
Than you can
_hubProxy.Invoke("Synx", new Stock({...);

Create and use the following value-returning methods in the application

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace HospitalCharges
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public const double dailycharges = 350;
double medcharges;
double surgcharges;
double labcharges;
double phyrehab;
double totalMiscCharges;
double totaldailycharges;
private object Output;
public MainWindow()
{
InitializeComponent();
}
public void CalcStayCharges(){
try
{
double numofdays = Convert.ToDouble(txtdays);
totaldailycharges = (double)dailycharges * numofdays;
}
catch { }
}
public void CalcMiscCharges()
{
try
{
medcharges = Convert.ToDouble(txtmedicalfee);
surgcharges = Convert.ToDouble(txtsurgicalfee);
labcharges = Convert.ToDouble(txtlabfee);
phyrehab = Convert.ToDouble(txtrehabfee);
totalMiscCharges = medcharges + surgcharges + labcharges + phyrehab;
}
catch { }
}
public void CalcTotalCharges()
{
double TotalCharges = totaldailycharges + totalMiscCharges;
}
public void BtnResult_Click(object sender, RoutedEventArgs e)
{
CalcStayCharges();
CalcMiscCharges();
CalcTotalCharges();``
Output = CalcTotalCharges();
}
}
}
//Create and use the following value-returning methods in the application:
// CalcStayCharges – calculates and returns the base charges for the hospital //stay. This is computed as $350 times the number of days in the hospital.
// CalcMiscCharges – calculates and returns the total of the medication, //surgical, lab, and physical rehabilitation charges
// CalcTotalCharges – calculates and returns the total charges.
Looks like you're missing the property for your arguments. Assuming the arguments in your Convert.To() are textBox controls, just add .Text next to their names to grab their text values. Return their values to a label, textBox or MessageBox. I'll go with a label for this example.
Create a label named "lbloutput" as requested by OP.
double medcharges;
double surgcharges;
double labcharges;
double phyrehab;
double totalMiscCharges;
double totaldailycharges;
double TotalCharges
.
.
.
public void CalcStayCharges()
{
try
{
double numofdays = Convert.ToDouble(txtdays.Text);
totaldailycharges = (double)dailycharges * numofdays;
}
catch { }
}
public void CalcMiscCharges()
{
try
{
medcharges = Convert.ToDouble(txtmedicalfee.Text);
surgcharges = Convert.ToDouble(txtsurgicalfee.Text);
labcharges = Convert.ToDouble(txtlabfee.Text);
phyrehab = Convert.ToDouble(txtrehabfee.Text);
totalMiscCharges = medcharges + surgcharges + labcharges + phyrehab;
}
catch { }
}
public void CalcTotalCharges()
{
TotalCharges = totaldailycharges + totalMiscCharges;
}
public void BtnResult_Click(object sender, RoutedEventArgs e)
{
foreach (TextBox txt in Controls.OfType<TextBox>())
{
if (txt.Text == "")
{
txt.Text = "0";
}
}
CalcStayCharges();
CalcMiscCharges();
CalcTotalCharges();
lbloutput.Text = "Your total charges are: " + TotalCharges.ToString("C");
}

Solve recursion and infinite loop issue

I am currently writing a program which reads data in from a text file. The problem I am currently having is that the CompareTo method below is coming up with the error System.StackOverflowException was unhandled and saying "Make sure you don't have an infinite loop or infinite recursion. This error appears on the line return name.CompareTo(temp.name);.
The whole class is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Country
{
public class Country : IComparable
{
// Country Properties
private String name;
private float gdpGrowth;
private float inflation;
private float tradeBalance;
private float hdiRanking;
private LinkedList<String> tradePartners;
//Constructor
public Country(String name, float gdpGrowth, float inflation, float tradeBalance, float hdiRanking, LinkedList<String> tradePartners)
{
this.name = name;
this.gdpGrowth = gdpGrowth;
this.inflation = inflation;
this.tradeBalance = tradeBalance;
this.hdiRanking = hdiRanking;
this.tradePartners = tradePartners;
}
public String Name
{
set { this.name = value; }
get { return name; }
}
public float GdpGrowth
{
set { this.gdpGrowth = value; }
get { return gdpGrowth; }
}
public float Inflation
{
set { this.inflation = value; }
get { return inflation; }
}
public float TradeBalance
{
set { this.tradeBalance = value; }
get { return tradeBalance; }
}
public float HdiRankings
{
set { this.hdiRanking = value; }
get { return hdiRanking; }
}
public LinkedList<String> TradePartners
{
set { this.tradePartners = value; }
get { return tradePartners; }
}
public override string ToString()
{
return name + ", " + gdpGrowth + ", " + inflation + ", " + tradeBalance + ", " + hdiRanking + ", " + tradePartners;
}
public int CompareTo(object other)
{
Country temp = (Country)other;
return name.CompareTo(temp.name);
}
}
}
The class which is calling the country class is...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Country
{
public partial class Form1 : Form
{
private AVLTree<Country> countryTree = new AVLTree<Country>();
public Form1()
{
InitializeComponent();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
// array to stroe each line of the file
String[] Lines = new string[1000];
String[] tempPartners = new string[1000];
int count = 0;
// Store each line of the file in the eachLine array
Lines = File.ReadAllLines("countries.csv");
foreach (String line in Lines)
{
if (count == 0)
{
count++;
}
else
{
// array to hold info
String[] info = new string[5];
//splits the countries
info = line.Split(',');
// split trade partners and puts in array
tempPartners = info[5].Split(';', '[', ']');
// insert current instance of country into AVL Tree
countryTree.InsertItem(new Country(info[0], float.Parse(info[1]),
float.Parse(info[2]), float.Parse(info[3]), float.Parse(info[4]), new LinkedList<String>(tempPartners)));
// create seperator
string seperator = ", ";
// stroe array
string partners = string.Join(seperator, tempPartners);
// remove first comma
partners = partners.Substring(1, partners.Length - 1);
//remove last comma
partners = partners.Remove(partners.Length - 2);
//pass in information from file into grid view
dataGridView1.Rows.Add(info[0], info[1], info[2], info[3], info[4], partners);
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
You've got infinite recursion going here. CompareTo makes a recursive call but doesn't terminate due to the lack of a base case, so the recursive stack grows infinite. No actual comparison takes place either. What integer values do you want this to return, and under what conditions?
Perhaps as CyberDude said, you're really trying to use String.Compare(name, temp.name)?

From a Class to a Form

EDIT: I have tried this a different way and updated my new code. I am now getting a few errors:
'Car_Class_BBrantley.Car.Car()' must declare a body because it is not marked abstract, extern, or partial
No overload for method 'GetCarData' takes 0 arguments
No overload for method 'GetCarData' takes 0 arguments
These last two errors fall under the GetCarData(); lines which are under the two button sections.
Alright, so my task is to create an application that displays 3 main features: year, make, and speed of a car. The year and make are inputted with textboxes and the speed starts at 0.
There is an accelerate button which is supposed to add 5 to the speed every time it is pressed and a brake button which decreases the speed by 5 every time it is pressed.
I am having trouble using the class and form together to display the results. I need to display in a messagebox the make, year, and speed. I have been sitting here for hours and I am getting nowhere. I am getting the errors " speed does not exist in current context" and "car does not exist in current context" under my buttons. I am unsure of how I should go about fixing this.
Any and all help is much appreciated. I'm sorry if this is a mess. I have never worked with classes before.
Here is the form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Car_Class_BBrantley
{
public partial class Form1 : Form
{
private Car myCar;
public Form1()
{
myCar = new Car;
InitializeComponent();
}
private void GetCarData(Car car)
{
try
{
myCar.Make = txtMake.Text;
myCar.Year = int.Parse(txtModel.Text);
myCar.Speed = 0;
}
catch (Exception ex)
{
MessageBox.Show(string.Concat("Must enter a valid make and year model for the car. ", ex.Message, "\r\n", ex.StackTrace));
}
}
private void btnAcc_Click(object sender, EventArgs e)
{
GetCarData();
myCar.AccSpeed(5);
MessageBox.Show(" Your car is a " + myCar.Year + myCar.Make + " and it is traveling " + myCar.Speed + " mph. ");
}
private void btnBrake_Click(object sender, EventArgs e)
{
GetCarData();
myCar.DecSpeed(5);
MessageBox.Show(" Your car is a " + myCar.Year + myCar.Make + " and it is traveling " + myCar.Speed + " mph. ");
}
}
}
If you would like to see the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Car_Class_BBrantley
{
class Car
{
private int year;
private string make;
private int speed;
public Car()
{
this.year = 1994;
this.make = "Ford";
this.speed = 0;
}
public Car(string make, int year, int speed)
{
this.year = year;
this.make = make;
this.speed = speed;
}
public string Make
{
get { return make; }
set { make = value; }
}
public int Year
{
get { return Year; }
set { Year = value; }
}
public int Speed
{
get { return speed; }
set { speed = value; }
}
public void AccSpeed(int speedIncrement)
{
//Add check for speed limit ranges
Speed += speedIncrement;
}
public void DecSpeed(int speedDecrement)
{
//Add check for speed limit ranges
Speed -= speedDecrement;
}
}
}
You haven't created an instance of the Car class.
In this method:
private void btnAcc_Click(object sender, EventArgs e)
{
GetCarData(car);
car.Accelerate += speed;
MessageBox.Show(" Your car is a " + car.year + car.make + " and it is traveling " + speed + " mph. ");
}
You're trying to do something with car (GetCarData(car))but... what car?
Create an instance of the Car class at the form level:
public partial class Form1 : Form
Car car = new Car();
.
.
You have to store the car somewhere within the form. If you need to use more cars, you should have some kind of collection, selecting a correct car depending on some of the parameters.
A simple example would be:
public partial class Form1 : Form
{
private Car _car;
public Form1()
{
_car = new Car();
InitializeComponent();
}
...
and then use the already created instance of car within the form, i.e.
private void btnAcc_Click(object sender, EventArgs e)
{
GetCarData(_car);
_car.Accelerate(); //note the way you were using won't work on this line
MessageBox.Show(" Your car is a " + _car.year + _car.make + " and it is traveling " + speed + " mph. ");
}
In my opinion, you may need to add another button to set the initial settings of the car, in that event handler method you initialize the car's Year, Speed and Model info by calling the GetCarData(). Then, remove the GetCarData() from the DecSpeed() and AccSpeed(), because you don't want to re-initialize everytime you Accelerate or Decelerate.

c# visual studio how to pass value from subclass to parent class?

I'm new here, and also new in C# programming in Visual Studio.
Currently I have an assignment about C# refactoring.
This is the original class
calculator.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace HUANG_Kai_30077528_Assign1
{
public partial class calculator : Form
{
public calculator()
{
InitializeComponent();
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
}
private void calorieCalculation()
{
if (rbtnMale.Checked)
{
txtCalories.Text = (66
+ (6.3 * Convert.ToDouble(txtWeight.Text))
+ (12.9 * ((Convert.ToDouble(txtFeet.Text) * 12)
+ Convert.ToDouble(txtInches.Text)))
- (6.8 * Convert.ToDouble(txtAge.Text))).ToString();
}
else
{
txtCalories.Text = (655
+ (4.3 * Convert.ToDouble(txtWeight.Text))
+ (4.7 * ((Convert.ToDouble(txtFeet.Text) * 12)
+ Convert.ToDouble(txtInches.Text)))
- (4.7 * Convert.ToDouble(txtAge.Text))).ToString();
}
}
private void weightCalculation()
{
double maleVariable = 50;
double femaleVariable = 45.5;
double Formula = (2.3 * (((Convert.ToDouble(txtFeet.Text) - 5) * 12) + Convert.ToDouble(txtInches.Text)));
if (rbtnMale.Checked)
{
txtIdealWeight.Text = ((maleVariable + Formula) * 2.2046).ToString();
}
else
{
txtIdealWeight.Text = ((femaleVariable + Formula) * 2.2046).ToString();
}
}
private void txtFeetValidation()
{
double feet;
if (!double.TryParse(txtFeet.Text, out feet))
{
MessageBox.Show("Feet must be a numeric value.");
txtFeet.Select();
if (!(Convert.ToDouble(txtFeet.Text) >= 5))
{
MessageBox.Show("Height has to be equal to or greater than 5 feet!");
txtFeet.Select();
return;
}
}
}
private void txtInchesValidation()
{
double inches;
if (!double.TryParse(txtInches.Text, out inches))
{
MessageBox.Show("Inches must be a numeric value.");
txtInches.Select();
return;
}
}
private void txtWeightValidation()
{
double weight;
if (!double.TryParse(txtWeight.Text, out weight))
{
MessageBox.Show("Weight must be a numeric value.");
txtWeight.Select();
return;
}
}
private void txtAgeValication()
{
double age;
if (!double.TryParse(txtAge.Text, out age))
{
MessageBox.Show("Age must be a numeric value.");
txtAge.Select();
return;
}
}
private void btnCalculate_Click(object sender, EventArgs e)
{
txtFeetValidation();
txtInchesValidation();
txtWeightValidation();
txtAgeValication();
//Clear old results
txtIdealWeight.Text = "";
txtCalories.Text = "";
calorieCalculation();
weightCalculation();
}
private void label8_Click(object sender, EventArgs e)
{
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnAddPatient_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(txtIdealWeight.Text))
{
Form secondForm = new patientInfo(this);
secondForm.Show();
}
else
{
MessageBox.Show("Please enter all datas and click on 'Add Patient' to add patient's records");
}
}
private void btnPatientList_Click(object sender, EventArgs e)
{
Form secondForm = new patientList(this);
secondForm.Show();
}
private void btnClear_Click(object sender, EventArgs e)
{
rbtnMale.Checked = false;
rbtnFemale.Checked = false;
txtFeet.Text = "";
txtInches.Text = "";
txtWeight.Text = "";
txtAge.Text = "";
txtCalories.Text = "";
txtIdealWeight.Text = "";
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
}
}
The following classed are the parent class and sub-classes I would like to setup.
parent: calculator.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace HUANG_Kai_30077528_Assign1
{
public partial class calculator : Form
{
//private string maleCaloriesCalculation();
//private string maleWeightCalculation();
//private string femaleCaloriesCalculation();
//private string femaleWeightCalculation();
public calculator()
{
InitializeComponent();
}
private void rbtnMale_CheckedChanged(object sender, EventArgs e)
{
}
private void btnCalculate_Click(object sender, EventArgs e)
{
//Clear old results
txtIdealWeight.Text = "";
txtCalories.Text = "";
/* Validate User Input: */
//Validate height (feet) is numeric value
double result;
if (!double.TryParse(txtFeet.Text, out result))
{
MessageBox.Show("Feet must be a numeric value.");
txtFeet.Select();
return;
}
//Validate height (inches) is numeric value
if (!double.TryParse(txtInches.Text, out result))
{
MessageBox.Show("Inches must be a numeric value.");
txtInches.Select();
return;
}
//Validate weight is numeric value
if (!double.TryParse(txtWeight.Text, out result))
{
MessageBox.Show("Weight must be a numeric value.");
txtWeight.Select();
return;
}
//Validate age is numeric value
if (!double.TryParse(txtAge.Text, out result))
{
MessageBox.Show("Age must be a numeric value.");
txtAge.Select();
return;
}
if (!(Convert.ToDouble(txtFeet.Text) >= 5))
{
MessageBox.Show("Height has to be equal to or greater than 5 feet!");
txtFeet.Select();
return;
}
/*End validation*/
calculation();
}
private void calculation()
{
if (rbtnMale.Checked)
{
txtCalories.Text = maleCalculator.maleCalories().ToString();
//txtCalories.Text = maleCalculator.maleCaloriesCalculation();
//txtIdealWeight.Text = maleCalculator.maleWeightCalculation();
}
else
{
txtCalories.Text = femaleCalculator.femaleCaloriesCalculation();
txtIdealWeight.Text = femaleCalculator.femaleWeightCalculation();
}
}
private void btnClear_Click(object sender, EventArgs e)
{
rbtnMale.Checked = false;
rbtnFemale.Checked = false;
txtFeet.Text = "";
txtInches.Text = "";
txtWeight.Text = "";
txtAge.Text = "";
txtCalories.Text = "";
txtIdealWeight.Text = "";
}
}
}
subclass: maleCalculation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HUANG_Kai_30077528_Assign1
{
class maleCalculator: calculator
{
//private string maleCaloriesCalculation;
//private string maleWeightCalculation;
public maleCalculator maleCalories()
{
(66 + (6.3 * Convert.ToDouble(txtWeight.Text))
+ (12.9 * ((Convert.ToDouble(txtFeet.Text) * 12)
+ Convert.ToDouble(txtInches.Text)))
- (6.8 * Convert.ToDouble(txtAge.Text))).ToString();
return maleCalories();
//this.txtCalories.Text = new maleCalculator.maleCalories;
}
public maleCalculator maleWeight()
{
((50 + (2.3 * (((Convert.ToDouble(txtFeet.Text) - 5) * 12)
+ Convert.ToDouble(txtInches.Text)))) * 2.2046).ToString();
return maleWeight();
}
}
}
subclass: femaleCalculation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HUANG_Kai_30077528_Assign1
{
class femaleCalculator : calculator
{
public double femaleCaloriesCalculation()
{
txtCalories.Text = (655 + (4.3 * Convert.ToDouble(txtWeight.Text))
+ (4.7 * ((Convert.ToDouble(txtFeet.Text) * 12)
+ Convert.ToDouble(txtInches.Text)))
- (4.7 * Convert.ToDouble(txtAge.Text))).ToString();
return femaleCaloriesCalculation();
}
public double femaleWeightCalculation()
{
txtIdealWeight.Text = ((45.5 + (2.3 * (((Convert.ToDouble(txtFeet.Text) - 5) * 12)
+ Convert.ToDouble(txtInches.Text)))) * 2.2046).ToString();
return femaleWeightCalculation();
}
}
}
As we can see, these two sub-classes are use to do the calculation for the calories and ideal weight. They are plan to take place of private void calorieCalculation() and private void weightCalculation() in the original class calculator.cs.
The function I need is like this:
When I execute the program and need to calculate the idealWeight and calories, the parent class calculator.cs will get the result from the formula contain in the sub-class, and ToString in the text box. That's why there are txtCalories and txtIdealWeight inside the calculator.cs.
So the question is how to get the results in the sub-class, and fill in the text boxes?
Guys, please help me with it as this is really important to me!!
Thank you all!!
Do you mean a virtual function? If so,
class Ancestor
{
public virtual int DoSomething()
{
// execute commands here.
// for now just throw exception.
throw new NotImplementedException();
}
}
class Derived_A : Ancestor
{
public override int DoSomething()
{
return 1 + 1;
}
}
class Derived_B : Ancestor
{
public override int DoSomething()
{
return 1 + 2;
}
}
This is ancestry, with virtual functions. For more on this:
Practical usage of virtual functions in c#
http://msdn.microsoft.com/en-us/library/9fkccyh4(v=vs.80).aspx
This type of code can also be done with interfaces. See http://msdn.microsoft.com/en-us/library/vstudio/ms173156.aspx.

Categories