Reputation: 15
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;
}
}
}
Upvotes: 0
Views: 168
Reputation: 3896
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
).
Upvotes: 1