C# Logic Issues

Hi,

Trying to write an app that will allow the user to input their MPH and the number of hours they have traveled.

So, 20 MPH * 1 = 20, 20 MPH * 2 = 40

This my logic, if I enter in 40 for MPH and 2 for hours, this just repeats 2 times with the calculation 40*2.

I want to increment is like what I did above, where did I mess up?

decimal MPH;
                decimal distance;
                decimal hours;
                int count = 1;
                if (decimal.TryParse(mphTextBox.Text, out MPH))
                {
                    if (decimal.TryParse(hoursTextBox.Text, out hours))
                        while (count <= hours)
                        {
                            distance = (MPH * hours);
                            distanceListBox.Items.Add(distance);
                            count++;
                        }
                }

Open in new window

LVL 3
Computer GuyAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

käµfm³d 👽Commented:
Youre calculating distance based on hours, which never changes. You need to be caculating against count.
0
it_saigeDeveloperCommented:
You don't need to loop the calculation.  A quick and dirty example:

Form1.cs -
using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace EE_Q28634325
{
	public partial class Form1 : Form
	{
		private bool fIsClosing;

		public Form1()
		{
			InitializeComponent();
		}

		private void OnLoad(object sender, EventArgs e)
		{
			tbHours.Enabled = string.IsNullOrEmpty(tbMPH.Text);
			btnCalculate.Enabled = false;
		}

		private void OnClick(object sender, EventArgs e)
		{
			if (!fIsClosing)
			{
				decimal mph = Convert.ToDecimal(tbMPH.Text);
				decimal hours = Convert.ToDecimal(tbHours.Text);
				decimal total = mph * hours;
				lbTotals.Items.Add(string.Format("You traveled {0} in {1} at {2} per hour.",
					total != 1 ? string.Format("{0} miles", total) : string.Format("{0} mile", total), 
					hours != 1 ? string.Format("{0} hours", hours) : string.Format("{0} hour", hours), 
					mph != 1 ? string.Format("{0} miles", mph) : string.Format("{0} mile", mph)));
				tbMPH.Clear();
				tbHours.Clear();
				tbHours.Enabled = btnCalculate.Enabled = false;
			}
		}

		private void OnValidating(object sender, CancelEventArgs e)
		{
			if (!fIsClosing)
			{
				if (sender is TextBox)
				{
					var tb = sender as TextBox;
					Decimal tempValue = -1;
					if (!Decimal.TryParse(tb.Text, out tempValue))
					{
						MessageBox.Show(string.Format("You must enter a numeric value in the {0} textbox.", tb.Equals(tbHours) ? "hours" : "miles per hour (MPH)"));
						e.Cancel = true;
					}
					else
					{
						if (tb.Equals(tbMPH))
							tbHours.Enabled = true;

						if (tb.Equals(tbHours))
							btnCalculate.Enabled = true;
					}
				}
			}
		}

		private void OnClosing(object sender, FormClosingEventArgs e)
		{
			fIsClosing = true;
		}
	}
}

Open in new window

Form1.Designer.cs -
namespace EE_Q28634325
{
	partial class Form1
	{
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && (components != null))
			{
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.lblMPH = new System.Windows.Forms.Label();
			this.tbMPH = new System.Windows.Forms.TextBox();
			this.tbHours = new System.Windows.Forms.TextBox();
			this.lblHours = new System.Windows.Forms.Label();
			this.lbTotals = new System.Windows.Forms.ListBox();
			this.btnCalculate = new System.Windows.Forms.Button();
			this.SuspendLayout();
			// 
			// lblMPH
			// 
			this.lblMPH.AutoSize = true;
			this.lblMPH.Location = new System.Drawing.Point(13, 13);
			this.lblMPH.Name = "lblMPH";
			this.lblMPH.Size = new System.Drawing.Size(158, 13);
			this.lblMPH.TabIndex = 0;
			this.lblMPH.Text = "Enter the Miles Per Hour (MPH):";
			// 
			// tbMPH
			// 
			this.tbMPH.Location = new System.Drawing.Point(177, 10);
			this.tbMPH.Name = "tbMPH";
			this.tbMPH.Size = new System.Drawing.Size(100, 20);
			this.tbMPH.TabIndex = 1;
			this.tbMPH.Validating += new System.ComponentModel.CancelEventHandler(this.OnValidating);
			// 
			// tbHours
			// 
			this.tbHours.Location = new System.Drawing.Point(177, 36);
			this.tbHours.Name = "tbHours";
			this.tbHours.Size = new System.Drawing.Size(100, 20);
			this.tbHours.TabIndex = 3;
			this.tbHours.Validating += new System.ComponentModel.CancelEventHandler(this.OnValidating);
			// 
			// lblHours
			// 
			this.lblHours.AutoSize = true;
			this.lblHours.Location = new System.Drawing.Point(13, 39);
			this.lblHours.Name = "lblHours";
			this.lblHours.Size = new System.Drawing.Size(156, 13);
			this.lblHours.TabIndex = 2;
			this.lblHours.Text = "Enter the time traveled in hours:";
			// 
			// lbTotals
			// 
			this.lbTotals.FormattingEnabled = true;
			this.lbTotals.Location = new System.Drawing.Point(16, 89);
			this.lbTotals.Name = "lbTotals";
			this.lbTotals.Size = new System.Drawing.Size(260, 160);
			this.lbTotals.TabIndex = 4;
			// 
			// btnCalculate
			// 
			this.btnCalculate.Location = new System.Drawing.Point(200, 63);
			this.btnCalculate.Name = "btnCalculate";
			this.btnCalculate.Size = new System.Drawing.Size(75, 23);
			this.btnCalculate.TabIndex = 5;
			this.btnCalculate.Text = "Calculate";
			this.btnCalculate.UseVisualStyleBackColor = true;
			this.btnCalculate.Click += new System.EventHandler(this.OnClick);
			// 
			// Form1
			// 
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(288, 264);
			this.Controls.Add(this.btnCalculate);
			this.Controls.Add(this.lbTotals);
			this.Controls.Add(this.tbHours);
			this.Controls.Add(this.lblHours);
			this.Controls.Add(this.tbMPH);
			this.Controls.Add(this.lblMPH);
			this.Name = "Form1";
			this.Text = "Form1";
			this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.OnClosing);
			this.Load += new System.EventHandler(this.OnLoad);
			this.ResumeLayout(false);
			this.PerformLayout();

		}

		#endregion

		private System.Windows.Forms.Label lblMPH;
		private System.Windows.Forms.TextBox tbMPH;
		private System.Windows.Forms.TextBox tbHours;
		private System.Windows.Forms.Label lblHours;
		private System.Windows.Forms.ListBox lbTotals;
		private System.Windows.Forms.Button btnCalculate;
	}
}

Open in new window

Produces the following output -Capture.JPGCapture.JPG-saige-
0
it_saigeDeveloperCommented:
Now saying that.  Kaufmed is correct, if you did want to loop the calculation, you would not want to calculate on hours.  As a matter of fact, all you would have to do is add the MPH to the distance:
decimal MPH;
decimal distance;
decimal hours;
int count = 1;
if (decimal.TryParse(mphTextBox.Text, out MPH) && decimal.TryParse(hoursTextBox.Text, out hours))
{
	while (count <= hours)
	{
		distance += MPH;
		distanceListBox.Items.Add(distance);
		count++;
	}
}

Open in new window

But then there is still a problem with this.  If someone enters 1.5 hours, you will end up with an inaccurate distance.

-saige-
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Computer GuyAuthor Commented:
How about making my result 56".0" adding the decimal at the end?
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.