Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need help on a windows based Inheritance

Status
Not open for further replies.

DarkWorlds

Technical User
Jul 20, 2005
64
US
Im supposed to be doing Inheritance on the console line, and well all is semi ok. But what im confused on is how do this in a windows design.

I am trying to complete something, but I dont even know where to start.

I was hoping someone could help me. Here are what I need for classes. And what they have to do. of course this all posts up on a listbox.

Ive tried this with console and for the most part i got it working, but it was static info in the code, but the same setup in windows i have no clue.

The base class will be Vehicle. The Car and Truck classes will inherit from the Vehicle class. The Vehicle class will be composed of an object of the FuelTank class. The FuelTank class has 2 attribute variables: (mTankCapacity and mCurrentValue).

In addition to the FuelTank object, the attribute variables of the Vehicle class are: mVehID, mDesc, mOdometer, and mMPG. In addition to setting up properties for the variables as needed, the Vehicle class has the following methods: AddFuel() - receives the amount of fuel to be added to the tank and adds that to the tank if the tank will hold it. If it will, it returns a true; otherwise, a false. FillTank() – fills the tank and returns a string indicating the amount of gallons added to the tank.

The attribute variable of the Car class is mNumRiders. The methods of the Car class are: getMPG() – a method that calculates the current MPG. The MPG is reduced by 2% for every rider over 1. (For example if the car's mpg is 28.5 and there are 5 riders, the current mpg is 26.22). MoveForward() – receives the mileage to move forward. The method determines if there is enough fuel to make the trip. If not, it returns false. If there is enough fuel to make the trip, the mileage is added to the odometer and the gas tank is reduced by the amount of gas needed for the trip.

The attribute variable of the Truck class is mLoadLbs. The methods of the Truck class are: getMPG() – a method that calculates the current MPG. The MPG is reduced by 3% for every thousand pounds if the load is >= 1,000 pounds. For example if the truck's mpg is 13.4 and is loaded with 4000 pounds, the current mpg is 11.79. Another example is if the truck's mpg is 13.4 loaded with 500 pounts, the current mpg is 13.4. MoveForward() – receives the mileage to move forward. The method determines if there is enough fuel to make the trip. If not, it returns false. If there is enough fuel to make the trip, the mileage is added to the odometer, the gas tank is reduced by the amount of gas needed for the trip, and the method returns true.

So thats the classes, go give a visual refrence there is a listbox, a move forward button and a add fuel button.

I would honestly love the help on where to go with this, I am so lost but yet i really need to see a sample of this coded. All the samples I have are in console (look around the web and they all are) I would just like to see a sample like this in a windows format, seeing how its way more confusing.

Please I am really looking for help, if you wish to email me then fine, or something. As long as i can figure out how this dumb program goes. This is what you get when you get a lab book to teach your self but no teacher edition. *sigh* I look forward to your help.
 
DarkWorlds,

We won't do your homework for you, but we can give you a step in the right direction.

Start by creating the vehicle class (right click on your windows project and select "Add Class". Call it vehicle and add the necessary properties and methods to it.

When that's done, create 2 more classes (Car and Truck) with the appropriate Properties as well.

Public class Truck : Vehicle
Public class Car : Vehicle

When you create these classes, you don't need to add the vehicle Properties because they are already there.


Once you have this done, you have all the necessary models for your program.


On your windows forms, design the Graphical User Interface (GUI) with listboxes, buttons, etc. I always find this the fun part!

Once you have the GUI created, you need to "wire it up". Create the required instances of Car and Truck on the form. Create the button events (by double clicking on the button on the form it will create the event for you in code) and begin the controlling of the cars/trucks.

For example:

public Car ToyotaCorolla = new Car(); //Corolla's have wicked mileage!

private void btnAddFuel_Click(object sender, EventArgs e)
{
ToyotaCorolla.AddFuel(20); //Add 20 to fuel
}

private void btnMoveForward_Click(object sender, EventArgs e)
{
if (ToyotaCorolla.MoveForward(50) == true) //Move car 50
{
Car.Odometer += 50; //Add 50 to the odometer
}
}

This should be enough to get you started. Most of your calculations seem to happen in the Car or Truck classes.

Let us know how it goes!
 
but how to wire it up.

Can you place up a demo of a program that has a similar setup? Im not asking people to do my work. But this is where I get lost. How do i get info to the screen.

The console is so much easier.

Anyways this is what I have thus far, I just wanted o test to see if my class worked if i made a new one from main. Im a very test kinda guy, I like to see that every little thing works. I so hate c# because its not logical to me at all. Anyways hows this looking? I honestly need to see a example to see how this is supposed to work in a windows form.

[STAThread]
static void Main()
{
Application.Run(new Form1());
}

private void btn_1_Click(object sender, System.EventArgs e)
{
lb_veh.Items.Clear();
Car c2 = new Car(213, Camery, 2345, 22.8, 5);
}

class Vehicle
{
private int mVehID;
private string mDesc;
private int mOdometer;
private double mMPG;

public Vehicle (int VehID, string Desc, int Odometer, double MPG)
{
mVehid = VehID;
mDesc = Desc;
mOdometer = Odometer;
mMPG = MPG;

// I would see if it writes it up to the list box here, but it wont.

}
}

class Car : Vechicle
{
private int mNumRiders;

}

class Truck : Vechicle
{
private double mloadpounds;
}

class MPG : Vechicle
{
private double mTankCapacity;
//private double mCurrentValue;
}
 
There are a couple of things you need to do yet to be able to see the Car in the ListBox. To display a string, a ListBox will call the object's ToString() method. For example, lets say I have a Dog class:
Code:
pubic class Dog
{
     private string myBreed;
     private string dogName;
     public Dog(string breed, string name)
     {
          myBreed = breed;
          dogName = name;
     }

     public override string ToString()
     {
          return(dogName);
     }
}

If I added a Dog() to a ListBox control...
Code:
Dog myPooch = new Dog("Lab","Scruffy");
ListBox kennel = new ListBox();
kennel.Items.Add(myPooch);

...the listbox would now display "Scruffy"

PS: FYI, when you create a class, it automatically inherits from Object. All objects have a ToString() method that is inherited from this class. You have to put the 'override' keyword in your ToString() method to override the one that is inherited.

Does any of this help?

--Brad
 
I am totaly lost, still nothing works. Im just trying to get the basics working before i add in all that other stuff I have to add in. Im so lost its unbelieable. Things say they dont need stuff, and others say they do. And apparently base doesnt work in the windows form mode?!

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace Lab1
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.ListBox lb_veh;
private System.Windows.Forms.Button btn_1;
private System.Windows.Forms.Button btn_2;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;

public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();

//
// TODO: Add any constructor code after InitializeComponent call
//
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (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.lb_veh = new System.Windows.Forms.ListBox();
this.btn_1 = new System.Windows.Forms.Button();
this.btn_2 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// lb_veh
//
this.lb_veh.ItemHeight = 16;
this.lb_veh.Location = new System.Drawing.Point(112, 40);
this.lb_veh.Name = "lb_veh";
this.lb_veh.Size = new System.Drawing.Size(352, 244);
this.lb_veh.TabIndex = 0;
//
// btn_1
//
this.btn_1.Location = new System.Drawing.Point(128, 320);
this.btn_1.Name = "btn_1";
this.btn_1.TabIndex = 1;
this.btn_1.Text = "Car";
this.btn_1.Click += new System.EventHandler(this.btn_1_Click);
//
// btn_2
//
this.btn_2.Location = new System.Drawing.Point(312, 336);
this.btn_2.Name = "btn_2";
this.btn_2.TabIndex = 2;
this.btn_2.Text = "Truck";
this.btn_2.Click += new System.EventHandler(this.btn_truck_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
this.ClientSize = new System.Drawing.Size(608, 478);
this.Controls.Add(this.btn_2);
this.Controls.Add(this.btn_1);
this.Controls.Add(this.lb_veh);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);

}
#endregion

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}

private void btn_1_Click(object sender, System.EventArgs e)
{
lb_veh.Items.Clear();
Car c2 = new Car(213, Camery, 2345, 5);
}

class Vehicle
{
private int mVehID;
private string mDesc;
private int mOdometer;
//private double mMPG;

public Vehicle (int VehID, string Desc, int Odometer)//, double MPG)
{
mVehid = VehID;
mDesc = Desc;
mOdometer = Odometer;
//mMPG = MPG;

// I would see if it writes it up to the list box here, but it wont.


public Veh (int VehID, string Desc, int Odometer)
{
VehID = mVehID;
Desc = mDesc;
Odometer = mOdometer;
}
public override string ToString()
{
ListBox lb_veh = new ListBox();
lb_veh.Items.Add(VehID);
}
}
}

class Car : Vechicle
{
private int mNumRiders;

public test1 (int VehID, string Desc, int odometer, int NumRiders)
{
base(VehID, Desc, odometer)
lb_veh.Items.Add(NumRiders);
}


}

class Truck : Vechicle
{
private double mloadpounds;
}

class MPG : Vechicle
{
private double mTankCapacity;
//private double mCurrentValue;
}

}
}
 
No need to panic, you have a good start. First off, lets get your code sorted out and put it into managable chunks. Here is what you've got:

1) Form1 - the form on which you are displaying your data
2) Vehicle - class you have created to represent an automobile
2) Car - inherits Vehicle

It is important that you see these three as separate 'objects', or entities, as C# is object-oriented. Each of these objects can only see things they contain. For example, Form1 is the only one of these three that can do anything with your btn_1 and lb_veh because they are in the Form1 class. Therefore, you can't put 'lb_veh.Items.Add(NumRiders);' in your Car class because it doesn't know what lb_veh is! Form1 does know what it is, however. Hint: When do you want to add a Car to the ListBox? Perhaps when you click a button...

Also, you need to look at your constructors. For example, here is your Car constructor
Code:
            public test1 (int VehID, string Desc, int odometer, int NumRiders)
            {
            base(VehID, Desc, odometer)
                lb_veh.Items.Add(NumRiders);
            }
Your constructor needs to be named the same as your class. This should be:
[code}
public Car (int VehID, string Desc, int odometer, int NumRiders)
{
base(VehID, Desc, odometer)
lb_veh.Items.Add(NumRiders);
}
[/code]
Your constructor is what is run when you create a new car:
Code:
Car c2 = new [b]Car(213, Camery, 2345, 5)[/b];
Be sure to check ALL of your constructors to make sure you did this. It is IMPORTANT!!!!

It is so much easier to break down these problems into small chunks and tackle problems one at a time than freak out over the whole program. If you get compiler errors, do a Google search on the error to see what it means. There are also tons of C# tutorials for beginners if you search hard enough on Google.

If you need clarification on any concepts, please post. However, just posting your whole program without any input on errors or anything and freaking out helps no one.

Hope this helps,
--Brad
 
Yeah I plan to be in on Sunday 11:30am - 5am (Central) Monday. I look forward to the help.

I am trying to look at the small concept. But I dont have any small windows concepts to look at. This is why im just hoping that i can get stuff to display. I hope to do it in small chunks :)

I just need people that are willing to stick around. I am thankfull for all the help I have reseved thus far. And I plan to continue useing this forum from here on out till I have the hang of this.

I hope no one minds
 
Ahh I need help... ive done alot, over 72 hours of just winging it, and trying to get help online.

First of all my error checks in car DO not work, but if I put them at the button they do? How can I fix this. Also my MPG isnt being updated when i put in passengers or load pounds. Im so lost... But yet the load pounds and the people change work. This verson currently does not work due to error checking :(. Please im in a mess, pulling out my hair trying to figure out why im so stupied!

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace Lab1
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;

car CAR = new car( 3, 15, 12, 199, "CAR", 22.1f, 78902.4f );
truck TRUCK = new truck( 3000, 30, 16, 169, "TRUCK", 18.1f, 4902.4f );
//disp_veh();
private System.Windows.Forms.ListBox lb_Veh;
private System.Windows.Forms.Button btn_Switch;
private System.Windows.Forms.Button btn_Move;
private System.Windows.Forms.TextBox tb_value;
private System.Windows.Forms.Label lbl_Combo;
private System.Windows.Forms.Button btn_Random;
private System.Windows.Forms.Button btn_Fuel;
private System.Windows.Forms.Button btn_Combo;
bool isCar = true;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();

//
// TODO: Add any constructor code after InitializeComponent call
//
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (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.lb_Veh = new System.Windows.Forms.ListBox();
this.btn_Switch = new System.Windows.Forms.Button();
this.btn_Move = new System.Windows.Forms.Button();
this.tb_value = new System.Windows.Forms.TextBox();
this.lbl_Combo = new System.Windows.Forms.Label();
this.btn_Random = new System.Windows.Forms.Button();
this.btn_Fuel = new System.Windows.Forms.Button();
this.btn_Combo = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// lb_Veh
//
this.lb_Veh.Location = new System.Drawing.Point(32, 16);
this.lb_Veh.Name = "lb_Veh";
this.lb_Veh.Size = new System.Drawing.Size(376, 173);
this.lb_Veh.TabIndex = 0;
//
// btn_Switch
//
this.btn_Switch.Location = new System.Drawing.Point(32, 208);
this.btn_Switch.Name = "btn_Switch";
this.btn_Switch.Size = new System.Drawing.Size(160, 24);
this.btn_Switch.TabIndex = 2;
this.btn_Switch.Text = "Switch Vehicle";
this.btn_Switch.Click += new System.EventHandler(this.btn_Switch_Click);
//
// btn_Move
//
this.btn_Move.Location = new System.Drawing.Point(248, 208);
this.btn_Move.Name = "btn_Move";
this.btn_Move.Size = new System.Drawing.Size(160, 23);
this.btn_Move.TabIndex = 3;
this.btn_Move.Text = "Move Forward";
this.btn_Move.Click += new System.EventHandler(this.btn_Move_Click);
//
// tb_value
//
this.tb_value.Location = new System.Drawing.Point(216, 376);
this.tb_value.Name = "tb_value";
this.tb_value.Size = new System.Drawing.Size(184, 20);
this.tb_value.TabIndex = 4;
this.tb_value.Text = "";
this.tb_value.Visible = false;
this.tb_value.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tb_value_KeyDown);
//
// lbl_Combo
//
this.lbl_Combo.Location = new System.Drawing.Point(24, 376);
this.lbl_Combo.Name = "lbl_Combo";
this.lbl_Combo.Size = new System.Drawing.Size(176, 23);
this.lbl_Combo.TabIndex = 5;
this.lbl_Combo.UseMnemonic = false;
//
// btn_Random
//
this.btn_Random.Location = new System.Drawing.Point(32, 264);
this.btn_Random.Name = "btn_Random";
this.btn_Random.Size = new System.Drawing.Size(160, 23);
this.btn_Random.TabIndex = 6;
this.btn_Random.Text = "Random Move";
this.btn_Random.Click += new System.EventHandler(this.btn_Random_Click);
//
// btn_Fuel
//
this.btn_Fuel.Location = new System.Drawing.Point(248, 264);
this.btn_Fuel.Name = "btn_Fuel";
this.btn_Fuel.Size = new System.Drawing.Size(160, 23);
this.btn_Fuel.TabIndex = 7;
this.btn_Fuel.Text = "Add Fuel";
//
// btn_Combo
//
this.btn_Combo.Location = new System.Drawing.Point(56, 320);
this.btn_Combo.Name = "btn_Combo";
this.btn_Combo.Size = new System.Drawing.Size(328, 23);
this.btn_Combo.TabIndex = 8;
this.btn_Combo.Visible = false;
this.btn_Combo.Click += new System.EventHandler(this.btn_Combo_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(440, 438);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.btn_Combo,
this.btn_Fuel,
this.btn_Random,
this.lbl_Combo,
this.tb_value,
this.btn_Move,
this.btn_Switch,
this.lb_Veh});
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);

}
#endregion

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
//disp_veh();
}

private void btn_Switch_Click(object sender, System.EventArgs e)
{
isCar = !isCar;
disp_veh();
}



public class fueltank
{
double mTankCapacity, mCurrentValue;

public fueltank()
{

}

public fueltank( double tank, double val )
{
mTankCapacity = tank;
mCurrentValue = val;
}

public double Tank
{
get
{
return mTankCapacity;
}
set
{
mTankCapacity = value;
}
}

public double Val
{
get
{
return mCurrentValue;
}
set
{
mCurrentValue = value;
}
}


}

public class vehicle
{
public fueltank FuelTank = new fueltank();
int mvehid;
string mvehdesc;
double mmpg, modometer;

public vehicle()
{

}

public vehicle( double tank, double cval, int id, string desc, double mpg, double odo )
{
FuelTank.Tank = tank;
FuelTank.Val = cval;

mVehID = id;
mVehDesc = desc;
mMPG = mpg;
mOdometer = odo;
}

public int mVehID;
public string mVehDesc;

public double mMPG
{
get
{
return mmpg;
}
set
{
mmpg = value;
}
}

public double mOdometer
{
get
{
return modometer;
}
set
{
modometer = value;
}
}

}

public class car : vehicle
{
int mnumriders;

public car()
{

}

public car( int pass, double tank, double cval, int id, string desc, double mpg, double odo) : base( tank, cval, id, desc, mpg, odo )
{
mNumRiders = pass;
}

public int mNumRiders
{
get
{
return mnumriders;
}
set
{
if (mnumriders > 0 || mnumriders < 6)
{
mnumriders = value;
}
else
{
MessageBox.Show(" You must enter a number between 0 and 6.",
"E R R O R", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}

}

}

public double getMPG()
{
return mMPG * (1-0.02 * mNumRiders);
}

public bool MOVE (double miles)
{
double reqGal = getMPG() * miles;
if (FuelTank.Val < reqGal)
{
return false;
}
else
{
mOdometer += miles;
FuelTank.Val -= reqGal;
return true;
}
}
}

public class truck : vehicle
{
double mloadlbs;

public truck()
{

}

public truck( double load, double tank, double cval, int id, string desc, double mpg, double odo) : base( tank, cval, id, desc, mpg, odo )
{
mLoadLbs = load;
}

public double mLoadLbs
{
get
{
return mloadlbs;
}
set
{
if (mloadlbs > 0 || mloadlbs < 8000)
{
mloadlbs = value;
}
else
{
MessageBox.Show(" You must enter a number between 0 and 8000 lbs.",
"E R R O R", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}

}
public double getMPG()
{
return mMPG * (1 - 0.03 * mLoadLbs / 1000.0);
}

public bool MOVE (double miles)
{
double reqGal = getMPG() * miles;
if (FuelTank.Val < reqGal)
{
return false;
}
else
{
mOdometer += miles;
FuelTank.Val -= reqGal;
return true;
}
}
}

public void disp_veh()
{
if ( isCar )
{
lb_Veh.Items.Clear();
lb_Veh.Items.Add("Vehicle ID: "+CAR.mVehID);
lb_Veh.Items.Add("Description: "+CAR.mVehDesc);
lb_Veh.Items.Add("Odometer Reading: "+CAR.mOdometer);
lb_Veh.Items.Add("MPG: "+CAR.mMPG);
lb_Veh.Items.Add("Tank Capacity: "+CAR.FuelTank.Tank);
lb_Veh.Items.Add("Current Value: "+CAR.FuelTank.Val);
lb_Veh.Items.Add("Number Riders: "+CAR.mNumRiders);

}
else
{
lb_Veh.Items.Clear();
lb_Veh.Items.Add("Vehicle ID: "+TRUCK.mVehID);
lb_Veh.Items.Add("Description: "+TRUCK.mVehDesc);
lb_Veh.Items.Add("Odometer Reading: "+TRUCK.mOdometer);
lb_Veh.Items.Add("MPG: "+TRUCK.mMPG);
lb_Veh.Items.Add("Tank Capacity: "+TRUCK.FuelTank.Tank);
lb_Veh.Items.Add("Current Value: "+TRUCK.FuelTank.Val);
lb_Veh.Items.Add("Load Pounds: "+TRUCK.mLoadLbs);

}
if ( isCar )
{
btn_Combo.Text = "Change Number of Riders";
btn_Combo.Visible = true;
lbl_Combo.Visible = false;
tb_value.Visible = false;
}
else
{
btn_Combo.Text = "Change Load Pounds";
btn_Combo.Visible = true;
lbl_Combo.Visible = false;
tb_value.Visible = false;
}

return;
}


private void btn_Move_Click(object sender, System.EventArgs e)
{
//CAR.forward(tb_value.Text);
}

private void btn_Combo_Click(object sender, System.EventArgs e)
{
if ( isCar )
{
lbl_Combo.Text = "Enter Number of Riders (1 - 6)";
lbl_Combo.Visible = true;
tb_value.Visible = true;

// get the value from tb_value
}
else
{
lbl_Combo.Text = "Enter load pounds (0 - 8000)";
lbl_Combo.Visible = true;
tb_value.Visible = true;

// get the value from tb_value
}
}

private void btn_Random_Click(object sender, System.EventArgs e)
{
// This will do a random number that will end up being the move distance.
}

private void tb_value_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if ( isCar )
{
int temp = Convert.ToInt32(tb_value.Text);
tb_value.Hide();
disp_veh();
}
else
{
double temp = Convert.ToDouble(tb_value.Text);
// if ( temp < 0 || temp > 8000)
// {
// MessageBox.Show(" You must enter a number between 0 and 8000 lbs.",
// "E R R O R", MessageBoxButtons.OK,
// MessageBoxIcon.Error);
// }
// else
// {
tb_value.Hide();
// TRUCK.mLoadLbs = temp;
disp_veh();
// }
}
}

}
}
}


 
First, a couple of general tidbits:
1. You need parentheses around your variables in your return statements.
Code:
return(true);
2. Instead of calling the class name and then the variable, use the keyword 'this'.
Code:
FuelTank.Tank = tank;
FuelTank.Val = cval;
should be...
Code:
this.Tanks = tank;
this.Val = cval;
3. It is bad coding practice to differentiate your class names and variables simply by using capital letters. You should not have a class named Car and a variable named car or CAR. This gets EXTREMELY confusing when someone is trying to read your code and decipher what is going on. The only items that should be capitalized are classes, and only constants should have ALLCAPS.
4. C# is a case-sensitive language. mLoadLbs is different than mloadlbs. I see many times in your program where your casing is inconsistent. This will cause the compiler not to recognize the variable, method, or class.

When you get your code cleaned up and post again, please give the line number(s) and errors you are getting on those lines. Also, don't post the InitializeComponents() procedure. You haven't written it so we don't need to look at it.

Good luck,
Brad
 
Brad,

You actually don't need parentheses around your return statement. return true; is fine in C#. It is however a practice adopted from C++;

DarkWorlds,

Tonight (EST) I will sit down and look over your code in detail. This is a simple project that you are trying to do - you just seem a little mixed up in the concepts. I'll try to give you a tutorial on this tomorrow/tonight.

In the meantime - do some more research on inheritance. Try to understand that concept.
 
Hmm, guess you need to kick and bite those old habits to get them to let go. I've never even bothered to try them without!

Thanks!
Brad
 
Well I would clean out the code, but im not even sure why and where any more. I can look at a test in console and have a cluw whats going on, it comes to this lab and im so mixed up because ive already put 60+ hours into it. This was after soemone helped me, and that was as far as I got with there help.
 
DarkWorlds,

I'm working on your app right now.
How flexible can the Windows Form be? does it have to be a listbox with 2 buttons?

Is there a FillTank button too?


I have set up a crap account so you can get a hold of me (and anyone else for that matter)

llamachant(at)yahoo(dot)ca

I wrote it like that so the forum doesn't get spammers and spiders.

I'll check my email often
 
You where emailed JurkMonkey. Thanks.

And thanks to everyone else thats helping me. I must have a thick skull or something. console makes since, and this doesnt... :(

And i tired cleaning it up a bit, and then got lost on what I was cleaning up, needless to say back to the old copy.
 
It accured to me, the use of the ovverride ToStrings need to be used instead of a called display which may help seeing how then I dont have to even worry about that class.

Heh... I dont know why I didnt do that before.
 
Yeah, the big thing you have to remember with using forms is you have to interact with your controls to get your input and output. Depending on the control, you can use the .Text property or the .ToString() method.
 
Ahh, the add fuel is wrong. dont know where. If you put in 2 it puts in 4, if you put in 1 it puts in 2. Help figure it out please

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace Lab1_5
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnSwitch;
private System.Windows.Forms.Button btnMove;
private System.Windows.Forms.Button btnRandom;
private System.Windows.Forms.Button btnFuel;
private System.Windows.Forms.Button btnChangeRiders_Pounds;
private System.Windows.Forms.RichTextBox rtxtVehicle;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
Car car = new Car(877,"Camry", 24567,28.5,15.4,12.6,5);
Truck truck = new Truck(124,"F-150",8754,13.4,26.6,10.3,4000.0);
private System.Windows.Forms.Label lblCombo;
private System.Windows.Forms.TextBox txtCombo;
Vehicle vehicle;

public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
vehicle = car;
Display();
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (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.btnSwitch = new System.Windows.Forms.Button();
this.btnMove = new System.Windows.Forms.Button();
this.btnRandom = new System.Windows.Forms.Button();
this.btnFuel = new System.Windows.Forms.Button();
this.btnChangeRiders_Pounds = new System.Windows.Forms.Button();
this.txtCombo = new System.Windows.Forms.TextBox();
this.lblCombo = new System.Windows.Forms.Label();
this.rtxtVehicle = new System.Windows.Forms.RichTextBox();
this.SuspendLayout();
//
// btnSwitch
//
this.btnSwitch.Location = new System.Drawing.Point(16, 136);
this.btnSwitch.Name = "btnSwitch";
this.btnSwitch.Size = new System.Drawing.Size(96, 23);
this.btnSwitch.TabIndex = 0;
this.btnSwitch.Text = "Switch Vehicles";
this.btnSwitch.Click += new System.EventHandler(this.btnSwitch_Click);
//
// btnMove
//
this.btnMove.Location = new System.Drawing.Point(176, 136);
this.btnMove.Name = "btnMove";
this.btnMove.Size = new System.Drawing.Size(96, 23);
this.btnMove.TabIndex = 1;
this.btnMove.Text = "Move Foward";
this.btnMove.Click += new System.EventHandler(this.btnMove_Click);
//
// btnRandom
//
this.btnRandom.Location = new System.Drawing.Point(16, 184);
this.btnRandom.Name = "btnRandom";
this.btnRandom.Size = new System.Drawing.Size(96, 23);
this.btnRandom.TabIndex = 2;
this.btnRandom.Text = "Random Move";
this.btnRandom.Click += new System.EventHandler(this.btnRandom_Click);
//
// btnFuel
//
this.btnFuel.Location = new System.Drawing.Point(176, 184);
this.btnFuel.Name = "btnFuel";
this.btnFuel.Size = new System.Drawing.Size(96, 23);
this.btnFuel.TabIndex = 3;
this.btnFuel.Text = "Add Fuel";
this.btnFuel.Click += new System.EventHandler(this.btnFuel_Click);
//
// btnChangeRiders_Pounds
//
this.btnChangeRiders_Pounds.Location = new System.Drawing.Point(56, 224);
this.btnChangeRiders_Pounds.Name = "btnChangeRiders_Pounds";
this.btnChangeRiders_Pounds.Size = new System.Drawing.Size(168, 23);
this.btnChangeRiders_Pounds.TabIndex = 8;
this.btnChangeRiders_Pounds.Text = "Change Number of Riders";
this.btnChangeRiders_Pounds.Click += new System.EventHandler(this.btnChange_Click);
//
// txtCombo
//
this.txtCombo.Location = new System.Drawing.Point(168, 272);
this.txtCombo.Name = "txtCombo";
this.txtCombo.TabIndex = 5;
this.txtCombo.Text = "";
this.txtCombo.Visible = false;
this.txtCombo.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtCombo_KeyDown);
//
// lblCombo
//
this.lblCombo.Location = new System.Drawing.Point(16, 272);
this.lblCombo.Name = "lblCombo";
this.lblCombo.Size = new System.Drawing.Size(128, 32);
this.lblCombo.TabIndex = 6;
this.lblCombo.Visible = false;
//
// rtxtVehicle
//
this.rtxtVehicle.Location = new System.Drawing.Point(16, 16);
this.rtxtVehicle.Name = "rtxtVehicle";
this.rtxtVehicle.ReadOnly = true;
this.rtxtVehicle.Size = new System.Drawing.Size(256, 96);
this.rtxtVehicle.TabIndex = 9;
this.rtxtVehicle.Text = "";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 317);
this.Controls.Add(this.rtxtVehicle);
this.Controls.Add(this.lblCombo);
this.Controls.Add(this.txtCombo);
this.Controls.Add(this.btnChangeRiders_Pounds);
this.Controls.Add(this.btnFuel);
this.Controls.Add(this.btnRandom);
this.Controls.Add(this.btnMove);
this.Controls.Add(this.btnSwitch);
this.Name = "Form1";
this.Text = "Vehicle Control System";
this.ResumeLayout(false);

}
#endregion

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());

}


public class Vehicle
{
private int mVehID;
private string sDesc;
private double mOdometer;
private double mMPG;
private FuelTank fueltank;
private double mCurrentValue;
public Vehicle(int vehID, string desc, double odometer, double tankCapacity,
double currentValue,double mpg)
{
mVehID = vehID;
sDesc = desc;
mOdometer = odometer;
mMPG = mpg;
fueltank = new FuelTank(tankCapacity,currentValue);
mCurrentValue = currentValue;
}
public bool AddFuel(double addGas)
{
double temp;
temp = addGas;
if(CurrentValue + temp > TankCapacity)
{
return false;
}
else
{
CurrentValue += addGas;
return true;
}
}
public override string ToString()
{
return String.Format("Vehicle ID: {0}\nDescription: {1}\nOdometer:" +
"{2:N}\nFuel Tank Capacity: {3:N}\nCurrent Value {4:N}",
VehID,Desc, Odometer, TankCapacity, CurrentValue);
}


public string FillTank()
{
double gallonsAdded;
gallonsAdded = TankCapacity - CurrentValue;
CurrentValue += gallonsAdded;
return String.Format("You added {0:N} gallons to the tank",
gallonsAdded);
}


public int VehID
{
get
{
return mVehID;
}
set
{
mVehID = value;
}
}


public string Desc
{
get
{
return sDesc;
}
set
{
sDesc = value;
}
}


public double Odometer
{
get
{
return mOdometer;
}
set
{
mOdometer = value;
}
}


public double MPG
{
get
{
return mMPG;
}
set
{
mMPG = value;
}
}


public double CurrentValue
{
get
{
return fueltank.CurrentValue;
}
set
{
fueltank.CurrentValue = value;
}
}


public double TankCapacity
{
get
{
return fueltank.TankCapacity;
}
set
{
fueltank.TankCapacity = value;
}
}
}

// public class FuelTank
// {
// private FuelTank fueltank;
// private double mCurrentValue;
// }

public class Car : Vehicle
{
private int mNumRiders;
public Car(int vehID, string desc, double odometer, double mpg,
double tankCapacity,double currentValue, int numRiders):
base (vehID, desc, odometer,tankCapacity,currentValue, mpg)
{
mNumRiders = numRiders;
}
public int NumRiders
{
get
{
return mNumRiders;
}
set
{
mNumRiders = value;
}
}
public double getMPG()
{
if(NumRiders > 1)
{
return MPG - ((MPG * .02)*(NumRiders - 1));
}
else
return MPG;
}
public bool MoveForward(double mile)
{
if(CurrentValue * getMPG() >= mile)
{
Odometer += mile;
CurrentValue = (CurrentValue * getMPG() - mile) / getMPG();
return true;
}
else
return false;
}
public override string ToString()
{
return base.ToString () + String.Format("\nMPG: {0:N}\nNumber Riders: {1}", getMPG(),NumRiders);
}

}


public class Truck : Vehicle
{
private double mLoadPounds;
public Truck(int vehID, string desc, double odometer, double mpg,
double tankCapacity,double currentValue, double loadPounds):
base (vehID, desc, odometer,tankCapacity,currentValue, mpg)
{
mLoadPounds = loadPounds;
}
public double LoadPounds
{
get
{
return mLoadPounds;
}
set
{
mLoadPounds = value;
}
}
public double getMPG()
{
if(LoadPounds >= 1000)
return MPG - ((MPG * .03)*(LoadPounds / 1000));
else
return MPG;
}
public bool MoveForward(double mileage)
{
if(CurrentValue * getMPG() >= mileage)
{
Odometer += mileage;
CurrentValue = (CurrentValue * getMPG() - mileage) / getMPG();
return true;
}
else
return false;
}
public override string ToString()
{
return base.ToString () + String.Format("\nMPG: {0:N}\nLoad Pounds: {1}", getMPG(),LoadPounds);
}
}


public class FuelTank
{
private double mTankCapacity;
private double mCurrentValue;
public FuelTank(double tankCapacity,double currentValue)
{
mTankCapacity = tankCapacity;
mCurrentValue = currentValue;
}

public double TankCapacity
{
get
{
return mTankCapacity;
}
set
{
mTankCapacity = value;
}
}

public double CurrentValue
{
get
{
return mCurrentValue;
}
set
{
mCurrentValue = value;
}
}
}


private void btnMove_Click(object sender, System.EventArgs e)
{
lblCombo.Text = "Enter Milage";
lblCombo.Show();
txtCombo.Show();
txtCombo.Focus();
}


private void btnRandom_Click(object sender, System.EventArgs e)
{
Random RandomNum = new Random();
int RandomMile = RandomNum.Next(0,301);
string message = String.Format("Moving foward {0} miles", RandomMile);
txtCombo.Hide();
lblCombo.Hide();
if(vehicle is Car)
{
if(car.MoveForward(RandomMile) == false)
{
MessageBox.Show("Not enough gas for trip of " + RandomMile + " miles",
"MILEAGE STATUS");
return;
}
else
MessageBox.Show(message,"MILEAGE STATUS",MessageBoxButtons.OK,
MessageBoxIcon.None);
}
else
{
if(truck.MoveForward(RandomMile) == false)
{
MessageBox.Show("Not enough gas for trip of " + RandomMile + " miles",
"MILEAGE STATUS");
return;
}
else
MessageBox.Show(message,"MILEAGE STATUS",MessageBoxButtons.OK,
MessageBoxIcon.None);
}
Display();
}
private void btnFuel_Click(object sender, System.EventArgs e)
{
txtCombo.Clear();
lblCombo.Text = "Enter amount of gas (0 to fill tank)";
lblCombo.Show();
txtCombo.Show();
txtCombo.Focus();

}
private void btnChange_Click(object sender, System.EventArgs e)
{
txtCombo.Clear();
if (btnChangeRiders_Pounds.Text == "Change Number of Riders")
{
lblCombo.Text = "Enter Number of Riders (1 - 6)";
lblCombo.Show();
txtCombo.Show();
txtCombo.Focus();
}
else if (btnChangeRiders_Pounds.Text == "Change Load Pounds")
{
lblCombo.Text = "Enter Load Pounds (0 - 8000)";
lblCombo.Show();
txtCombo.Show();
txtCombo.Focus();
}
}


private void txtCombo_KeyDown(object sender, System.Windows.Forms.KeyEventArgs combo)
{
double input = 0;
//txtCombo.Clear();
if(combo.KeyCode == Keys.Enter)
{
try
{
input = double.Parse(txtCombo.Text);
}
catch(FormatException)
{
MessageBox.Show("Invaild Input","ERROR",MessageBoxButtons.OK,
MessageBoxIcon.Error);
txtCombo.Clear();
txtCombo.Focus();
return;
}
if(lblCombo.Text == "Enter Milage")
{
if(input < 0)
{
MessageBox.Show("No Negitive Numbers","ERROR",MessageBoxButtons.OK,
MessageBoxIcon.Error);
txtCombo.Clear();
txtCombo.Focus();
}
else
{
if(vehicle is Car)
{
if(car.MoveForward(input) == false)
{
MessageBox.Show("Not enough gas for trip of " + input + " miles",
"MILEAGE STATUS");
txtCombo.Clear();
txtCombo.Focus();
return;
}
else
{
txtCombo.Hide();
lblCombo.Hide();
}

}
else
{
if(truck.MoveForward(input) == false)
{
MessageBox.Show("Not enough gas for trip of " + input + " miles",
"MILEAGE STATUS");
txtCombo.Clear();
txtCombo.Focus();
return;
}
else
{
txtCombo.Hide();
lblCombo.Hide();
}
}
}
}
else if(lblCombo.Text == "Enter amount of gas (0 to fill tank)")
{
if(input < 0)
{
MessageBox.Show("No negitive numbers","ERROR",MessageBoxButtons.OK,
MessageBoxIcon.Error);
txtCombo.Clear();
txtCombo.Focus();
}
else
{
if(vehicle is Car)
{
if(input == 0)
MessageBox.Show(car.FillTank(),"Gas Status");
else if(car.AddFuel(input) == true)
{
car.AddFuel(input);
txtCombo.Hide();
lblCombo.Hide();
}
else
{
MessageBox.Show("Too much feul in the tank for that much gas","ERROR",MessageBoxButtons.OK,
MessageBoxIcon.Error);
txtCombo.Clear();
}
}
else
{
if(input == 0)
MessageBox.Show(truck.FillTank(),"Gas Status");
else if(truck.AddFuel(input) == true)
{
truck.AddFuel(input);
txtCombo.Hide();
lblCombo.Hide();
}
else
MessageBox.Show("Too much fuel for tank","ERROR",MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
else if(vehicle is Car)
{
//lblCombo.Text == "Enter Number of Riders (1 - 6)";
if(input < 1 || input > 6)
{
MessageBox.Show("Invalid Number of Riders","ERROR",MessageBoxButtons.OK,
MessageBoxIcon.Error);
txtCombo.Clear();
txtCombo.Focus();
return;
}
else
{
car.NumRiders = (int)input;
car.getMPG();
txtCombo.Clear();
txtCombo.Hide();
lblCombo.Hide();
}
}
else if(vehicle is Truck)
{
//lblCombo.Text == "Enter Load Pounds (0 - 8000)";
if(input < 0 || input > 8000)
{
MessageBox.Show("Invalid Load Pounds","ERROR",MessageBoxButtons.OK,
MessageBoxIcon.Error);
txtCombo.Clear();
txtCombo.Focus();
return;
}
else
{
truck.LoadPounds = input;
truck.getMPG();
txtCombo.Clear();
txtCombo.Hide();
lblCombo.Hide();
}
}

}
Display();
}


private void btnSwitch_Click(object sender, System.EventArgs e)
{
txtCombo.Clear();
txtCombo.Hide();
lblCombo.Hide();
if (vehicle is Car)
{
btnChangeRiders_Pounds.Text = "Change Load Pounds";
vehicle = truck;
}

else if (vehicle is Truck)
{
btnChangeRiders_Pounds.Text = "Change Number of Riders";
vehicle = car;
}
Display();
}


private void Display()
{
if(vehicle is Car)
rtxtVehicle.Text = car.ToString();
else
rtxtVehicle.Text = truck.ToString();

}
}
}
// Special thanks to Doug Manton for the help
// And all the online tutors that I may have missed.
 
Code:
else if(car.AddFuel(input) == true)
{
     car.AddFuel(input);
     txtCombo.Hide();
     lblCombo.Hide();
}

Your problem has to do with the statement above. When AddFuel returns true, you are adding the input value to your fuel tank twice. Let's say the fuel tank currently has a value of 5 in it when you hit your if statment.

Tank = 5

Now, lets say the user entered 2 for your input variable. Let's increment through the code.

Code:
else if (car.AddFuel(input) == true)

This calls your AddFuel method, adds the 'input' value to the tank, and returns true. Even though this is returning a bool, it STILL adds the input to the tank. So after this executes...

Tank = 7

Code:
     car.AddFuel(input);
     txtCombo.Hide();
     lblCombo.Hide();
...The rest of your code is run, AND AddFuel is called again! This adds the input value to the tank. So..

Tank = 9

...effectively doubling the amount of fuel that was supposed to be added.

Restructuring your if statement should fix your problem.
Code:
if(!car.AddFuel(input))
{
    MessageBox.Show("Too much fuel in tank for that much gas");
}
else
{
    txtCombo.Hide();
    lblCombo.Hide();
}

Note: When dealing with bool variables and if/loop statments, you can just say..

if(myBool)

...and if myBool is true, the stuff in the if statement will execute. A '!' means 'not', so if I have...

if(!myBool)

...then if myBool is false, the if statement will execute.

Just something to save you a little typing in the future.

Hope this is clear and helps,
--Brad
 
brd24gor that cleared alot up

Now the next question, put I need to know if I need to make a new thread. I need to make this program polymorphic, because this way I can see the difference before I have to construct a polymorpic program with employees.

Again im being asked to do this in a windows form, but only have console code. Atleast by useing my old sample above, I would have a windows form code to look at.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top