我有一个可以编译的工作应用程序。两个按钮工作,但我需要它们每次单击加速/减少速度5,目前他们只会让我点击一次加速给我一个5的速度答案,而减速给出-5。如何更改此设置以允许单击每个按钮并且速度更新多次?
以下是表格:
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. ";
}
}
}
这是班级:
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;
}
}
}
答案 0 :(得分:1)
由于这可能是家庭作业,我只是给出提示。使用这两个点击功能,您拨打的第一个电话是GetCarData()
。在GetCarData()
内,您正在调用myCar.Speed = 0;
,因此每次点击都会回到原点并不奇怪。
假设您只需要一个Car
个实例用于整个应用程序,您只需要修改GetCarData()
的内容(或者不做)你的内容想。只需对该功能进行一些调整,我会让你试验一下,你会很高兴。
但是,如果您想在应用中使用多个Car
个对象,则需要将其修改为某种List
(或者更好,IDictionary
)