Ok so I am trying to use a try catch to handle error in this simple gas mileage calculator. When I enter some number that are not in the error handeling like
gas = 8.97
begning miles = 853
end miles = 1235
it gives the right result so thats fine, but when I enter 0 for gas or for end miles it retures infinity.
also when I try to see if it will catch negative numbers or if begining miles is larger than end mileage it goes about the calculation anyway regardless of what the code wants to do.What is wrong with this?
gas = 8.97
begning miles = 853
end miles = 1235
it gives the right result so thats fine, but when I enter 0 for gas or for end miles it retures infinity.
also when I try to see if it will catch negative numbers or if begining miles is larger than end mileage it goes about the calculation anyway regardless of what the code wants to do.What is wrong with this?
Code:
try
{
float gas = float.Parse(textBox1.Text);
float bMile = float.Parse(textBox2.Text);
float eMile = float.Parse(textBox3.Text);
//if gas or endmiles is 0
if (gas == 0 )
{
this.label6.Text = "Gallons is zero ";
}
if(eMile == 0)
{
this.label6.Text = "Ending Mileage is zero ";
}
//see if begining mileage is larger than ending mileage
if (bMile >= eMile)
{
this.label6.Text = "End mileage less than begin mileage ";
}
//if negative values are entered
if (gas < 0)
{
this.label6.Text = "Gallons is negative ";
}
if (bMile < 0)
{
this.label6.Text = "Begning Miles is negative ";
}
if (eMile < 0)
{
this.label6.Text = "Ending Miles is negative ";
}
this.label6.Text = String.Format("Result: {0}", (eMile - bMile) / gas);
}
catch (FormatException ex)
{
// string was not a number, handle the error or just use a formatted text box,
// NumericUpDown, etc.
}