EDIT: I have tried this a different way and updated my new code. I am now getting a few errors:
'Car_Class_BBrantley.Car.Car()' must declare a body because it is not marked abstract, extern, or partial
No overload for method 'GetCarData' takes 0 arguments
No overload for method 'GetCarData' takes 0 arguments
These last two errors fall under the GetCarData(); lines which are under the two button sections.
Alright, so my task is to create an application that displays 3 main features: year, make, and speed of a car. The year and make are inputted with textboxes and the speed starts at 0.
There is an accelerate button which is supposed to add 5 to the speed every time it is pressed and a brake button which decreases the speed by 5 every time it is pressed.
I am having trouble using the class and form together to display the results. I need to display in a messagebox the make, year, and speed. I have been sitting here for hours and I am getting nowhere. I am getting the errors " speed does not exist in current context" and "car does not exist in current context" under my buttons. I am unsure of how I should go about fixing this.
Any and all help is much appreciated. I'm sorry if this is a mess. I have never worked with classes before.
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(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. ");
}
}
}
If you would like to see 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;
}
}
}
You haven't created an instance of the Car class.
In this method:
private void btnAcc_Click(object sender, EventArgs e)
{
GetCarData(car);
car.Accelerate += speed;
MessageBox.Show(" Your car is a " + car.year + car.make + " and it is traveling " + speed + " mph. ");
}
You're trying to do something with car (GetCarData(car))but... what car?
Create an instance of the Car class at the form level:
public partial class Form1 : Form
Car car = new Car();
.
.
You have to store the car somewhere within the form. If you need to use more cars, you should have some kind of collection, selecting a correct car depending on some of the parameters.
A simple example would be:
public partial class Form1 : Form
{
private Car _car;
public Form1()
{
_car = new Car();
InitializeComponent();
}
...
and then use the already created instance of car within the form, i.e.
private void btnAcc_Click(object sender, EventArgs e)
{
GetCarData(_car);
_car.Accelerate(); //note the way you were using won't work on this line
MessageBox.Show(" Your car is a " + _car.year + _car.make + " and it is traveling " + speed + " mph. ");
}
In my opinion, you may need to add another button to set the initial settings of the car, in that event handler method you initialize the car's Year, Speed and Model info by calling the GetCarData(). Then, remove the GetCarData() from the DecSpeed() and AccSpeed(), because you don't want to re-initialize everytime you Accelerate or Decelerate.
Related
I'm sending info from 3 input fields on a mobile app made in Unity (Coded in C#) to Firebase database, but as you can see it seems to send each input field's data individually then stacks it on top of one another.See attached Ideally I'd only want the last set of complete information.
using System.Collections;
using System.Collections.Generic;
using Proyecto26;
using UnityEngine;
using UnityEngine.UI;
public class PlayerScores : MonoBehaviour
{
public InputField dateText;
public InputField classText;
public InputField informationText;
User user = new User();
public static string Information;
public static string Class;
public static string Date;
// Start is called before the first frame update
private void Start()
{
}
public void OnSubmit()
{
Date = dateText.text;
PostToDatabase();
{
Class = classText.text;
PostToDatabase();
}
{
Information = informationText.text;
PostToDatabase();
}
}
public void OnGetScore()
{
RetrieveFromDatabase();
}
private void PostToDatabase()
{
User user = new User();
RestClient.Put("https://anti-bullying-demo.firebaseio.com/" + Date + Class + Information + ".json", user);
}
private void RetrieveFromDatabase()
{
RestClient.Get<User>("https://anti-bullying-demo.firebaseio.com/" + Date + Class + Information + ".json").Then(response =>
{
user = response;
});
}
}
In your OnSubmit() function call, you call PostToDatabase() three times - you only need call it once at the end.
public void OnSubmit()
{
Date = dateText.text;
{
Class = classText.text;
}
{
Information = informationText.text;
}
PostToDatabase();
}
Among the functions provided by LeanTween,
Is there a function that functions like iTeeen's RotateBy?
(RotateBy(GameObject obj,Hashtable hash))
What I want to do is,
After completing the animation, the function is executed through the string.
For example, in a card-matching game,
If you click on the card, the following event will occur.
WordReviewManager.cs:
public void onTuchHandler(object obj, EventArgs e)
{
TouchEventTypes t_evt = e as TouchEventTypes;
Debug.Log("GameObject : " + t_evt.go + " / " + "Card : " + t_evt.card);
Debug.Log("Card Index : " + t_evt.card_idx + " / " + "Card UniqueIndex : " + t_evt.card_snum);
Debug.Log("================================================================================");
WordReviewUtil.testAni(this.gameObject, t_evt.go, t_evt.card, t_evt.delay, t_evt.complete);
}
The function that receives the event is shown below.
WordReviewUtil.cs:
public static Hashtable testAni(GameObject listener, GameObject go, Card card, float delay = 0f, string complete = "testGood")
{
Debug.Log("hello TEST ANIMATION ~~ ");
Hashtable hash = new Hashtable();
GameObject goz = go as GameObject;
Debug.Log("goz >>>> " + goz);
hash.Add("gameObj", goz);
hash.Add("onComplete", complete);
return hash;
}
Here is what I expect to see afterwards.
WordReviewManager.cs:
public void testGood(Hashtable table)
{
Debug.Log("hello Moto ~?!");
}
That is, the testGood function is executed.
iTween has a function that gives me the functionality I want.
Immediately, RotateBy function.
But I am currently using the LeanTween library, not iTween.
Also, the LeanTween library does not provide the functionality I want.
I just need to call the function. Without any parameters.
How do I implement what I want to implement?
The main design change between iTween and LeanTween for the complete callback is that iTween takes the method name as string and internally calls the evil SendMessage method.
LeanTween uses the Action delegate, which can be considered as pointer to a method. You can see in WordReviewManager.Start() how you can just assign the testGood method to the field Action onCompleteCallback of TouchEventTypes and feed that into your system.
public class Card : MonoBehaviour { }
public class TouchEventTypes : EventArgs
{
public Card card;
public float delay;
public Action onCompleteCallback;
}
public class WordReviewManager : MonoBehaviour
{
void Start()
{
TouchEventTypes e = new TouchEventTypes();
e.onCompleteCallback = testGood;
//TODO: feed this into your touch event system.
}
public void testGood()
{
Debug.Log("hello Moto ~?!");
}
public void onTouchHandler(object obj, EventArgs e)
{
TouchEventTypes eventArgs = e as TouchEventTypes;
WordReviewUtil.RotateCard(
card: eventArgs.card,
delay: eventArgs.delay,
callback: eventArgs.onCompleteCallback
);
}
}
public static class WordReviewUtil
{
public static void RotateCard(Card card, float delay, Action callback)
{
LTDescr tween = LeanTween.rotateAround(card.gameObject,
axis: new Vector3(0,0,1),
add: 360f,
time: 2.0f
).setDelay(delay);
tween.setOnComplete(callback);
}
}
I am trying to do an assignment given but I am failing to do so. I wrote a product class and made a flower from it. Then I want to raise an event when flower quantity falls below 20, It should give me a warning. I think I am having difficulty in raising the event. I am sure I made the declerations of delegate and event correct but something is missing. Thank you in advance.
This line
flower.StockDecreased();
gives me this error:
Error 3 The event 'StokTakip.Product.StockDecreased' can only appear on the left hand side of += or -= (except when used from within the type 'StokTakip.Product')
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StokTakip
{
class Program
{
static void FlowerStockDecreased()
{
Console.WriteLine("Flower stock decreased");
}
static void Main(string[] args)
{
Product flower = new Product("Flower", 50);
Console.WriteLine(flower);
flower.StockDecreased += new Product.FlowerEventHandler(FlowerStockDecreased);
while (true)
{
Console.WriteLine("What is your choice");
Console.WriteLine("[1] Stock entry quantity ");
Console.WriteLine("[2] Stock exit quantity: ");
int choice = Convert.ToInt32(Console.ReadLine());
if (choice == 1)
{
Console.Write("Enter stock entry quantity: ");
flower.quantity += Convert.ToInt32(Console.ReadLine());
}
else if (choice == 2)
{
Console.Write("Enter stock exit quantity: ");
flower.quantity -= Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine(flower);
if (flower.quantity<20)
{
flower.StockDecreased(); //????
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StokTakip
{
public class Product
{
public string name;
public int quantity;
public Product(string a, int m)
{
name = a;
quantity = m;
}
public override string ToString()
{
return "Name: "+ this.name + " Stock Quantity: " + this.quantity;
}
public delegate void FlowerEventHandler();
public event FlowerEventHandler StockDecreased;
}
}
The error message is pretty clear. You can not raise an event like that. Only the declaring class can call the event like this and thus raise the event. All other classes can only add (+=) or remove (-=) event handlers from the event.
What you can do is put a public method into the Product class that raises the event like this:
public void RaiseStockDecreased()
{
if (StockDecreased != null)
StockDecreased();
}
You could call that externally.
But then again, this contradicts proper design, as I'd expect the Product class itself to determine whether stock was increased or decreased and raise the proper events. Otherwise you have to implement that logic in every place you want to be notified about stock changes.
Your product class should look something like this:
public class Product
{
public event FlowerEventHandler StockDecreased;
private int _quantity;
public int Quantity
{
get { return _quantity; }
set
{
int newQuantity = value;
if (newQuantity < _quantity)
{
if (StockDecreased != null) StockDecreased();
}
_quantity = newQuantity;
}
}
// Other stuff
}
Though a better pattern might be to have a StockChange method that can just check whether the change is positive or negative and raise the appropriate event.
I am currently writing a program which reads data in from a text file. The problem I am currently having is that the CompareTo method below is coming up with the error System.StackOverflowException was unhandled and saying "Make sure you don't have an infinite loop or infinite recursion. This error appears on the line return name.CompareTo(temp.name);.
The whole class is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Country
{
public class Country : IComparable
{
// Country Properties
private String name;
private float gdpGrowth;
private float inflation;
private float tradeBalance;
private float hdiRanking;
private LinkedList<String> tradePartners;
//Constructor
public Country(String name, float gdpGrowth, float inflation, float tradeBalance, float hdiRanking, LinkedList<String> tradePartners)
{
this.name = name;
this.gdpGrowth = gdpGrowth;
this.inflation = inflation;
this.tradeBalance = tradeBalance;
this.hdiRanking = hdiRanking;
this.tradePartners = tradePartners;
}
public String Name
{
set { this.name = value; }
get { return name; }
}
public float GdpGrowth
{
set { this.gdpGrowth = value; }
get { return gdpGrowth; }
}
public float Inflation
{
set { this.inflation = value; }
get { return inflation; }
}
public float TradeBalance
{
set { this.tradeBalance = value; }
get { return tradeBalance; }
}
public float HdiRankings
{
set { this.hdiRanking = value; }
get { return hdiRanking; }
}
public LinkedList<String> TradePartners
{
set { this.tradePartners = value; }
get { return tradePartners; }
}
public override string ToString()
{
return name + ", " + gdpGrowth + ", " + inflation + ", " + tradeBalance + ", " + hdiRanking + ", " + tradePartners;
}
public int CompareTo(object other)
{
Country temp = (Country)other;
return name.CompareTo(temp.name);
}
}
}
The class which is calling the country class is...
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;
using System.IO;
namespace Country
{
public partial class Form1 : Form
{
private AVLTree<Country> countryTree = new AVLTree<Country>();
public Form1()
{
InitializeComponent();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
// array to stroe each line of the file
String[] Lines = new string[1000];
String[] tempPartners = new string[1000];
int count = 0;
// Store each line of the file in the eachLine array
Lines = File.ReadAllLines("countries.csv");
foreach (String line in Lines)
{
if (count == 0)
{
count++;
}
else
{
// array to hold info
String[] info = new string[5];
//splits the countries
info = line.Split(',');
// split trade partners and puts in array
tempPartners = info[5].Split(';', '[', ']');
// insert current instance of country into AVL Tree
countryTree.InsertItem(new Country(info[0], float.Parse(info[1]),
float.Parse(info[2]), float.Parse(info[3]), float.Parse(info[4]), new LinkedList<String>(tempPartners)));
// create seperator
string seperator = ", ";
// stroe array
string partners = string.Join(seperator, tempPartners);
// remove first comma
partners = partners.Substring(1, partners.Length - 1);
//remove last comma
partners = partners.Remove(partners.Length - 2);
//pass in information from file into grid view
dataGridView1.Rows.Add(info[0], info[1], info[2], info[3], info[4], partners);
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
You've got infinite recursion going here. CompareTo makes a recursive call but doesn't terminate due to the lack of a base case, so the recursive stack grows infinite. No actual comparison takes place either. What integer values do you want this to return, and under what conditions?
Perhaps as CyberDude said, you're really trying to use String.Compare(name, temp.name)?
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;
}
}
}
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).