Why is my division operation returning 0? - c#

this is my first question on this website, thanks for helping. I have a web application I'm trying to make, but it always returns 0 whenever I do a division operation. The end goal is to get the correct output and display it to my label on my webpage, and whenever I do a simple operation for testing, like 1+2, it is correct. Here's some code, this first block refers to the webpage logic itself.
public partial class Length : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (IsValid)
{
Conversion convertObj = new Conversion();
double userIntLength = double.Parse(txtLengthInput.Text);
double convertedLength = convertObj.Length;
lblResult.Text = convertedLength.ToString();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlLength.SelectedIndex == 1)
{
lblUnits.Text = "Miles";
}
if (ddlLength.SelectedIndex == 2)
{
lblUnits.Text = "Kilometers";
}
if (ddlLength.SelectedIndex == 3)
{
lblUnits.Text = "Feet";
}
if (ddlLength.SelectedIndex == 4)
{
lblUnits.Text = "Yard";
}
if (ddlLength.SelectedIndex == 5)
{
lblUnits.Text = "Centimeters";
}
if (ddlLength.SelectedIndex == 6)
{
lblUnits.Text = "Inches";
}
}
}
Here is the business layer logic, and also where I think the issue is.
public class Conversion
{
double length;
public double Length
{
get
{
double total = (((double) length) / 1.609344);
return total;
}
set
{
length = value;
}
}
}
Doing some google-fu, everyone says it's because of the data types, but everything is casted into double so I'm not sure why that is happening.

You are never actually setting the length value in the Conversion class, if defaults to 0, so the answer will always be 0

You never assign a value to Conversion.Length property, so the Conversion.length field value is 0 and 0 / 1.609344 is still 0.
You may change your code to
Conversion convertObj = new Conversion();
convertObj.Length = double.Parse(txtLengthInput.Text);
double convertedLength = convertObj.Length;
BTW
In the Length getter you cast the length field to double although it is already decalred as double. So this is useless, and you can simply write
public class Conversion
{
double length;
public double Length
{
get
{
double total = length / 1.609344;
return total;
}
set
{
length = value;
}
}
}

Related

Method not passing result back to main program

Having some real trouble understanding where I've gone wrong here. I've marked in the code what and where. I am using an XAML interface and do have objects for everything here. The code compiles but the TextBlock will not update with the result from updateVTCShortCode Thanks for the help!
MAIN PROGRAM
namespace VTCPT
{
/// <summary>
///
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
public void shortFormCodec_SelectionChanged(object sender, RoutedEventArgs e)
{
//UPDATE THE SHORTCODE TEXTBLOCK
updateVTCShortCode display = new updateVTCShortCode();
display.mergeShortCode(longFormCodec.SelectedItem.ToString());
if (String.IsNullOrEmpty(display.finalResult()))
{ shortFormCodec.Text = ".."; }
else { shortFormCodec.Text = display.finalResult();
shortFormCodec.Text = "test";
} /////THIS IS NOT ACTUALLY GETTING A RETURN
}
public void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void updateShortForm(object sender, SelectionChangedEventArgs e)
{
}
private void TextBlock_SelectionChanged(object sender, RoutedEventArgs e)
{
}
private void fsSiteBuild_SelectionChanged(object sender, RoutedEventArgs e)
{
}
private void updateSiteBuild(object sender, TextChangedEventArgs e)
{
int index = fsRoomDesig.Text.IndexOf(".");
if (index > 0)
{ fsSiteBuild.Text = fsRoomDesig.Text.Substring(0, index); }
else { fsSiteBuild.Text = ".."; }
}
private void vtcSystemName_SelectionChanged(object sender, RoutedEventArgs e)
{
}
}
}
updateVTCShortCode CLASS
namespace VTCPT
{
class updateVTCShortCode
{
String result = "";
public void mergeShortCode(String longFormCodec)
{ if (longFormCodec.Equals("Cisco SX80"))
{
String sendShortForm = "SX80";
result = "V-T" + sendShortForm;
}
if (longFormCodec.Equals("Cisco Webex Codec Plus"))
{
String sendShortForm = "SRK";
result = "V-T" + sendShortForm;
}
if (longFormCodec.Equals("Cisco Webex Codec Pro"))
{
String sendShortForm = "SRK";
result = "V-T" + sendShortForm;
}
}
public String finalResult()
{ return result; } //////SHOULD BE GETTING SENT BACK TO MAIN PROGRAM
}
}
I think the problem is that in the following code taken from your shortFormCodec_SelectionChanged method. You set shortFormCodec.Text = display.finalResult(); immediately followed by shortFormCodec.Text = "test";. The final result will never be visible because it is being immediately overwritten with "test".
if (String.IsNullOrEmpty(display.finalResult()))
{
shortFormCodec.Text = "..";
}
else
{
shortFormCodec.Text = display.finalResult();
shortFormCodec.Text = "test";
}
As TheGeneral suggested in the comments, you should be able to identify this using breakpoints and stepping through the code (using the F8 key) while watching the values of your variables and text fields. If you hover your mouse over the variables and the .Text section of any shortFormCodec.Text line it will show you its value at that point in the program.
However, I think you may find it helpful if you adjust your code to use an if {} else if {} else {} structure. I would also change the finalResult() method to a property as it's doing nothing but return a string. For example:
class updateVTCShortCode
{
// You could set the default value to an empty string I.e. = ""
// but having it set to "Not set" may help you spot any problems for now.
// As long as you remember to call mergeShortCode() first, you would never
// see "Not set" returned anyway. But this would help you spot that mistake.
public string FinalResult { get; set; } = "Not set";
public void mergeShortCode(String longFormCodec)
{
if (longFormCodec.Equals("Cisco SX80"))
{
String sendShortForm = "SX80";
FinalResult = "V-T" + sendShortForm;
}
else if (longFormCodec.Equals("Cisco Webex Codec Plus"))
{
String sendShortForm = "SRK";
FinalResult = "V-T" + sendShortForm;
}
else if (longFormCodec.Equals("Cisco Webex Codec Pro"))
{
String sendShortForm = "SRK";
FinalResult = "V-T" + sendShortForm;
} else
{
// If longFormCodec is not matched, set the result to ".."
FinalResult = "..";
}
}
By setting the final result to ".." in the else block of the mergeShortCode() method and setting a default value for the FinalResult property (even if it is an empty string I.e. ""). You are preventing FinalResult ever being null and providing all possible outcomes from the one function. This means you can simplify the shortFormCodec_SelectionChanged() method to the following and easily reuse the mergeShortCode() method elsewhere:
public void shortFormCodec_SelectionChanged(object sender, RoutedEventArgs e)
{
//UPDATE THE SHORTCODE TEXTBLOCK
updateVTCShortCode display = new updateVTCShortCode();
display.mergeShortCode(longFormCodec.SelectedItem.ToString());
shortFormCodec.Text = display.FinalResult;
}
}

Need to use created class to create an instance and use it in a Form.cs file

So, I'm at a loss here. Have a small project to work on. Have to create a trip class then create a Windows Form app and use the class I created to use the form to calculate miles per gallons used and Cost Per Mile.
Have completed the class:
namespace TripCalculator
{
class Trip
{
//Data members of class
private string destination;
private double distTrav;
private double totalCostGas;
private double numGallonsGas;
//Default Constructor
public Trip()
{
}
//Constructor with all parameters
public Trip(string tripDest, double milesTrav, double ttlPriceGas, n double numGalls)
{
destination = tripDest;
distTrav = milesTrav;
totalCostGas = ttlPriceGas;
numGallonsGas = numGalls;
}
//Propery for destination data field
public string Destination
{
set
{
destination = value;
}
get
{
return destination;
}
}
public double DistTrav
{
set
{
distTrav = value;
}
get
{
return distTrav;
}
}
public double TotalCostGas
{
set
{
totalCostGas = value;
}
get
{
return totalCostGas;
}
}
public double NumGallonsGas
{
set
{
numGallonsGas = value;
}
get
{
return numGallonsGas;
}
}
public double CalculateMPG()
{
return (distTrav / numGallonsGas);
}
public double CalculateCPM()
{
return (totalCostGas / numGallonsGas);
}
public override string ToString()
{
return CalculateMPG().ToString();
}
}
}
I want to be able to input destination, distance, cost, and gallons of gas into the form. Then I want the mpg and cost per mile to return to me in a textboxes.
Here's the form.cs
namespace TripCalculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void calcBtn_Click(object sender, EventArgs e)
{
string destination;
double distTrav;
double totalCostGas;
double numGallonsGas;
destBox.Focus();
distBox.Focus();
gasBox.Focus();
galBox.Focus();
Trip aTrip = new Trip (destination, distTrav, totalCostGas, numGallonsGas );
mpgTxt.Text = aTrip.CalculateMPG().ToString();
cpmTxt.Text = aTrip.CalculateCPM().ToString();
destBox.Enabled = false;
}
}
}
Im getting 4 errors saying "Use of unassigned local variable 'destination' (As well as for the other 3 variables above). It'll start the program, but returns nothing when I type in the text boxes and click the button. What am I doing wrong? Please help! Thanks.
private void calcBtn_Click(object sender, EventArgs e)
{
string destination; // Give value for these
double distTrav; // Give value for these
double totalCostGas; // Give value for these
double numGallonsGas; // Give value for these
}
Assign some value, either from user input or hard coded value for testing
Something like the code below, where you get the values from the text box in your Winform assuming you have such text boxes.
string destination = DestinationTextBox.Text;
double distTrav = double.Parse(DistTravTextBox.Text);
double totalCostGas = double.Parse(TotalCostGasTextBox.Text);
double numGallonsGas = double.Parse(NumGallonsGasTextBox.Text);
You need to set the textbox values for the variables
string destination = txtDestination.Text;
double distTrav = double.Parse(txtTrav.Text);
double totalCostGas = double.Parse(txtCostGas.Text);
double numGallonsGas = double.Parse(GallonsGas.Text);

Creating a "Car" class with Accelerate method, and associate Accel and Decel buttons on form with created class

Taking a C#.Net class and we have been introduced a new concept of using a class with a form. It's an online class and basically the instructor has given us instructions, however they are somewhat unclear, at least to me. Unfortunately, his responses to students questions are very vague and basically, in a nut shell, told us to figure it out, so I be here. Below is what the instructor gave us.
=========================================================================
UML: Model: String, CurrentSpeed: Decimal, TopSpeed: Decimal, and Accelerate (change speed: Decimal)
Accelerate adds changeSpeed (which can be positive, negative or 0) to CurrentSpeed. CurrentSpeed can never exceed TopSpeed or be less than 0
e.g. if CurrentSpeed is 10 and dChangeSpeed is -20, CurrentSpeed becomes 0
General Requirements:
Top Speed combo box is filled with numbers 60, 70, 80 …. 200
(at Run time)
Change Speed combo box is filled with numbers 1, 2, 3 ….200
(at Run time)
User must select from combo box (cannot enter own numbers)
Button Action Requirements:
Accelerate For same model, increases Current Speed by Change Speed
For new model, sets Current Speed to Change Speed
(Current Speed can’t exceed Top Speed)
Decelerate For same model, decreases Current Speed by Change Speed
For new model, sets Current Speed to 0
(Current Speed can’t go below 0)
UML diagram is followed exactly.
Work (calculations, etc) done in the class, not the form.
=========================================================================
Ok, so my question is, should I use a Deceleration method, along with the Accelerate in the class? I'm assuming that each button (decel, accel) would need its own method in the class. However I think I'm overly making this complicated, which was the answer to one of my question I asked my instructor. I guess I'm totally stumped as to how to reference the class, specifically the Accelerate with the form.
So far, this is what I came up with, which I know is mostly wrong, however this is a beginners class from what I'm told and the support form the instructor is not there other than relying on a chapter about classes.
public class Car
{
// Backing Fields (Instance Variables)
private string _model;
private int _currentSpeed;
private int _topSpeed;
public int SpeedResult;
// Set Parameters
public Car()
{
this.Model = "";
this.CurrentSpeed = 0;
this.TopSpeed = 0;
}
// Constructor
public Car(string Model, int CurrentSpeed, int TopSpeed)
{
_model = Model;
_currentSpeed = CurrentSpeed;
_topSpeed = TopSpeed;
}
// Model Property
public string Model
{
get { return _model; }
set { _model = value; }
}
// Current Speed Property
public int CurrentSpeed
{
get { return _currentSpeed; }
set { _currentSpeed = value; }
}
// Top Speed Property
public int TopSpeed
{
get { return _topSpeed; }
set { _topSpeed = value; }
}
// Methods
public int Accelerate()
{
SpeedResult = (TopSpeed + CurrentSpeed);
return SpeedResult;
}
//
public void clear()
{
Model = "";
CurrentSpeed = 0;
TopSpeed = 0;
}
}
Form:
public partial class carSpeedForm : Form
{
private Car _myCar;
private int SpeedResult;
public carSpeedForm()
{
_myCar = new Car();
InitializeComponent();
}
private void carSpeedForm_Load(object sender, EventArgs e)
{
// Loads Amount ComboBox with values from 60 to 200 in increments of 10
for (int i = 60; i <= 200; i += 10)
topSpeedComboBox.Items.Add(i);
// Loads Amount ComboBox with values from 1 to 200 in increments of 1
for (int i = 1; i <= 200; i += 1)
changeSpeedComboBox.Items.Add(i);
}
private void GetCarData()
{
try
{
_myCar.Model = carModelTextBox.Text;
_myCar.TopSpeed = int.Parse(topSpeedComboBox.Text);
_myCar.CurrentSpeed = int.Parse(changeSpeedComboBox.Text);
}
catch
{
MessageBox.Show(string.Concat("Please enter a valid model and speed(s) for vehicle.","\r\n"));
}
}
private void accelButton_Click(object sender, EventArgs e)
{
GetCarData();
speedResultLabel.Text = SpeedResult.ToString("n1");
carResultLabel.Text = String.Format("Your car is a new car.");
}
private void decelButton_Click(object sender, EventArgs e)
{
GetCarData();
speedResultLabel.Text = SpeedResult.ToString("n1");
carResultLabel.Text = String.Format("Your car is a new car.");
}
private void clearButton_Click(object sender, EventArgs e)
{
//Clear textbox, combobox, labels
carModelTextBox.Clear();
carModelTextBox.Focus();
topSpeedComboBox.SelectedIndex = -1;
changeSpeedComboBox.SelectedIndex = -1;
speedResultLabel.Text = "";
carResultLabel.Text = "";
}
private void exitButton_Click(object sender, EventArgs e)
{
//Close application
this.Close();
}
}
Not only is your code not “mostly wrong”, I’d even call it mostly right. It is not clear exactly what you are asking, or what “how to reference the class” means.
The instructor is right to tell you to “to figure it out”, and we can’t do your assignment for you. If you have working code you want people to review, post it on the Code Review site.
However, there are a few code smells that, in my experience, will lead to problems in the future:
// Backing Fields (Instance Variables)
Do not comment programming terms; they contribute nothing and soon go out of sync with the code. Only comment things that cannot be expressed in the programming language.
private string _model;
// Model Property
public string Model
{
get { return _model; }
set { _model = value; }
}
That’s about the most verbose way possible to define a property. Defining separate backing fields only encourages people to use the backing field instead of the property. Moreover, making it public makes any consumer of the class able to change the property at any time. Sometimes you need those things, but you should not allow them unless you absolutely need them. Also, vague names like “Model” are hard to understand, especially if other classes use them. A better definition would be:
public string ModelName { get; private set; }
­
public int SpeedResult;
What is this? It’s not in your UML, and is never used for anything. Moreover, it’s public so anything can change it to anything; it’s totally useless, get rid of it.
// Set Parameters
public Car()
{
this.Model = "";
this.CurrentSpeed = 0;
this.TopSpeed = 0;
}
And then in your form constructor:
_myCar = new Car();
This is worse than useless; you’re creating instances that contain no data, and every field is public so anything can change your data to anything. C# gives you the ability to enforce that your instances only contain valid data. Use them, and only create an instance when you know its data. You should have only one Car constructor like this:
public Car(string modelName, float topSpeed)
{
if (string.IsNullOrWhiteSpace(modelName)) throw new ArgumentNullException("modelName");
ModelName = modelName;
TopSpeed = topSpeed;
}
I assume CurrentSpeed is mutable, so you probably shouldn’t define it in the constructor; it is a candidate for one of those public properties I warned you about.
public int Accelerate()
{
SpeedResult = (TopSpeed + CurrentSpeed);
return SpeedResult;
}
Why would you add TopSpeed to CurrentSpeed? That can make SpeedResult greater than TopSpeed. Why are your speeds ints? Your description calls them “decimal”, but the C# decimal type is for fixed-point values. float is a better choice.
Your question says “Accelerate adds changeSpeed ... to CurrentSpeed ... CurrentSpeed can never exceed TopSpeed or be less than 0”. So do that:
public void Accelerate(float changeSpeed)
{
var predictedSpeed = CurrentSpeed + changeSpeed;
if (predictedSpeed > TopSpeed)
CurrentSpeed = TopSpeed;
else if (predictedSpeed < 0)
CurrentSpeed = 0;
else
CurrentSpeed = predictedSpeed;
}
­
public void clear()
{
Model = "";
CurrentSpeed = 0;
TopSpeed = 0;
}
Again, you're allowing anything at all to wreck your data. Don't do that; if you need to create a new car, then create a new Car. If you don’t want to display a car, don’t create one.
There are problems with your carSpeedForm as well, but I see MGM is addressing those.
Reading the description you wrote, it looks like you basically have the concept down. From your form, I assume you will be selecting a car type? If that is the case, you basically want to define all your model(Car) behavior in a Car class.
For example, as you have already done, you would want to define accessors for the selected cars data and the Accelerate and Decelerate methods. That way inside you view(carSpeedForm) you can call the perspective method when the corresponding button is pressed. I.E. if the user presses the Accelerate button on the form, you would call the Accelerate method of the instance of Car. Hope that helps. You're not far off.
You should use the button and input controls to store the data in your_myCar instances. For Example
public partial class CarForm : Form
{
private Car theCar;
private bool modelChanged;
public CarForm()
{
theCar = new Car();
InitializeComponent();
loadChangeSpeed_cb();
loadTopSpeed_cb();
modelChanged = false;
}
private void loadChangeSpeed_cb()
{
for (decimal i = 1; i <= 200; i++)
{
changeSpeed_cb.Items.Add(i);
}
}
private void loadTopSpeed_cb()
{
for(decimal i = 60; i <= 200; i+=10)
{
topSpeed_cb.Items.Add(i);
}
}
private void accel_b_Click(object sender, EventArgs e)
{
if(modelChanged)
{
theCar.CurrentSpeed = theCar.ChangeSpeed;
modelChanged = false;
}
else
{
var si = changeSpeed_cb.SelectedItem;
if (si == null)
{
return;
}
theCar.Accelerate((decimal)si);
}
}
private void decel_b_Click(object sender, EventArgs e)
{
if(modelChanged)
{
theCar.CurrentSpeed = 0;
modelChanged = false;
return;
}
else
{
var si = changeSpeed_cb.SelectedItem;
if (si == null)
{
return;
}
theCar.Accelerate(-(decimal)si);
}
}
private void topSpeed_cb_SelectedIndexChanged(object sender, EventArgs e)
{
var si = topSpeed_cb.SelectedItem;
if(si == null)
{
return;
}
theCar.TopSpeed = (decimal)si;
}
private void changeSpeed_cb_SelectedIndexChanged(object sender, EventArgs e)
{
var si = changeSpeed_cb.SelectedItem;
if (si == null)
{
return;
}
theCar.ChangeSpeed = (decimal)changeSpeed_cb.SelectedItem;
}

How do I add calculations to my GUI in C#?

This is my first time using Windows Forms on Visual Studio with C#. I am trying to make my form have a button where when you click "Calculate Amount Due" that it will put what was calculated into the "Amount Due" field. But, anytime I say "textBox3 = aOrder.AmountDue()", it says it can not convert double to System.Windows.Forms.TextBox. How do I convert this appropriately? Here is my code for the program.
namespace MidTermPizzas
{
class pizzaOrder
{
public int numberOfCokes
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}
public int numberOfPizzas
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}
public double InputOrder()
{
const double COKE_PRICE = 1.49;
const double PIZZA_PRICE = 7.99;
double inputOrder = (numberOfCokes * COKE_PRICE) + (numberOfPizzas * PIZZA_PRICE);
return InputOrder();
}
public double TaxDue()
{
const double TAX = .073;
double taxDue = (this.InputOrder() * TAX);
return TaxDue();
}
public double GetAmountDue()
{
double getAmountDue = this.InputOrder() + this.TaxDue();
return GetAmountDue();
}
public double GetAmountPaid()
{
double getAmountPaid;
return GetAmountPaid();
}
public double GetChargeDue()
{
double getChargeDue = this.GetAmountDue() - this.GetAmountPaid();
return GetAmountPaid();
}
}
}
namespace MidTermPizzas
{
public partial class Form1 : Form
{
pizzaOrder aOrder = new pizzaOrder();
DailySummary aSummary = new DailySummary();
public Form1()
{
InitializeComponent();
}
//click File, Exit
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Enjoy your pizza!");
this.Close();
}
//click View, All Orders Placed
private void allOrdersToolStripMenuItem_Click(object sender, EventArgs e)
{
AllOrdersPlaced myForm = new AllOrdersPlaced();
myForm.Show();
}
//click View, Summary of Orders Placed
private void summaryOfOrdersToolStripMenuItem_Click(object sender, EventArgs e)
{
SummaryOfOrdersPlaced myForm2 = new SummaryOfOrdersPlaced();
myForm2.Show();
}
//text in box to the right of "Amount Due"
private void textBox3_TextChanged_1(object sender, EventArgs e)
{
textBox3 = aOrder.GetAmountDue();
}
}
}
textBox3.Text = Convert.ToString(aOrder.AmountDue());
Assuming AmountDue() is returning a Double.
You had two problems, you were trying to set the actual textbox object to a string instead of the .Text property of the textbox, and you aren't converting the double to a string.
textBox3 is the object. The object has various methods (to do stuff) and properties (to hold stuff), specifically textBox3.Text which is where you can set the text in the box. Remember MSDN is your friend.
To avoid this error, it's necessary assign the value Order.GetAmountDue() for Text property. This property contains the value of TextBox:
textBox3.Text = aOrder.GetAmountDue();
Because it's necessary keep the compatibility between the types, so you can't assign a Double for a TextBox, but you can assign a Double to a string (in this case the Text property its a string).
Maybe you need format the value, for more information see this link:
Double.ToString
In addition to the Textbox issue, I also don't think you should be returning the public method itself.ie
instead of
public double TaxDue()
{
const double TAX = .073;
double taxDue = (this.InputOrder() * TAX);
return TaxDue();
}
You should have
public double TaxDue()
{
const double TAX = .073;
double taxDue = (this.InputOrder() * TAX);
return taxDue;
}
The first implementation doesn't make sense.

Trouble calling a method from a class

Can anybody help me with this?:
I'm trying call a method from a my class "numbers" to show that if the entered number is over 50, on button click a message box shows displaying "high" but if it's below 50 it displays "low".
I can't figure out what i'm doing wrong here.
This is the code from my class:
private int number;
private string getNumber(int num)
{
number = num;
return number.ToString();
}
public int numProperty
{
get { return number; }
set { number = value; }
}
public void isHighorlow()
{
if (number >=50)
{
}
else
{
return;
}
}
Note: the int "number" is property that gets it's value from a text box too.
& here is the code from my form:
numbers info = new numbers();
private void Btn_Click(object sender, EventArgs e)
{
info.numProperty = Convert.ToInt32(numberBOX.Text);
info.isHighorlow = Messagebox.Show = ("High");
}
I know that I've not added the "low" bit yet because i'm still trying to see how this works. Sorry if it seems confusing as i'm still learning c#.
I get the error message: cannot assign isHighorlow because it's part of a method group.
And I also realise it's much easier if I just do an if statement on the textbox, but I'm practising Classes and Methods so I'm trying to do it this way.
thanks.
I'm guessing you want something like this:
public string isHighorlow(int number)
{
if (number >=50)
{
return "High";
}
else
{
return "Low";
}
}
numbers info = new numbers();
private void Btn_Click(object sender, EventArgs e)
{
Messagebox.Show(info.isHighorlow(Convert.ToInt32(numberBOX.Text)))
}
IsHighOrLow should be as follows
public bool isHighorlow()
{
if (number >=50)
{
return true;
}
else
{
return false;
}
}
And in button click
if (info.isHighorlow){
//say high
} else
{
// say low
}
isHighorLow is a method, not a property.
MessageBox.Show is a method.
Not sure what you are trying to do but it should be :
if(info.isHigh(Convert.ToInt32(numberBox.Text)))
Messagebox.Show("High");
else
Messagebox.Show("Low");
Meaning you have a method isHigh like so:
public bool isHigh()
{
return number>=50
}
(disclaimer: double check boolean and associated constants per C#)
isHighOrLow doesn't do anything at all. Perhaps this would be better:
public boolean isHigh()
{
if (number >=50)
{
return true;
}
else
{
return false;
}
}
Or, more concisely:
public boolean isHigh()
{
return number >=50;
}
When you call it, this might be closer to what you need:
numbers info = new numbers();
private void Btn_Click(object sender, EventArgs e)
{
info.numProperty = Convert.ToInt32(numberBOX.Text);
if (info.isHigh())
{
Messagebox.Show("High");
}
else
{
Messagebox.Show("Low");
}
}
In your class you have defined void isHighorlow().
This means that you have a method that returns nothing.
Of course such method cannot be used on the left part of an expression like you have done.
Probably you want to write in your class
public bool isHighorlow()
{
if (number >=50)
{
return true;
}
else
{
return false;
}
}
in this way you declare a method that return True if the internal value is >= 50 or false otherwise.
Now, in your form you can use the method in this way
Messagebox.Show(info.isHighorlow() ? "High" : "Low");
However, if the requirement is simply to return a flag for true or false, it is better to use a read only property changing the class code in this way
public bool isHighorlow()
{
get
{
return (number >=50 ? true : false);
}
// No set, read only
}
Try to change your code this way:
private int _number;
private string GetNumber(int number)
{
_number = number;
return number .ToString();
}
public int Number
{
get { return _number; }
set { _number = value; }
}
public string IsHigh()
{
get { if (number >= 50) return true; }
}
numbers info = new numbers();
private void Btn_Click(object sender, EventArgs e)
{
info.Number = Convert.ToInt32(numberBOX.Text);
MessageBox.Show(info.IsHigh ? "High" : "Low");
}

Categories

Resources