创建一个包含速度、模型和品牌的汽车类
本文关键字:模型 品牌 汽车类 速度 包含 一个 创建 | 更新日期: 2023-09-27 17:59:21
在将()添加到Car实例化后,我得到了一个新错误。上面写着:
"Car_Class_BBrantley.Form1.myCar()"必须声明主体,因为它没有标记为抽象、外部或分部错误出现在第14行。
好吧,所以我的任务是创建一个显示3个主要功能的应用程序:年份、品牌和汽车速度。年份和品牌通过文本框输入,速度从0开始。
有一个加速按钮,每次按下速度都会增加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(Car car)
{
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);
MessageBox.Show(" 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);
MessageBox.Show(" 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;
}
}
}
更改
private Car myCar();
至
private Car myCar;
和
private void GetCarData(Car car)
至
private void GetCarData()
更改
myCar = new Car;
to myCar = new Car();