I'm new using C# and I'm building a remote control. I got stuck and my code is not compiling. Please I need suggestions and how can I improve my code.
I think its Console.Readline() but I'm not sure how to use it. Also how can change this to 2 primary classes?
public class testRemote
{
public static bool PowerOn(bool powerStatus)
{
if (powerStatus == true)
{
testRemote.DisplayMessage("TV already on");
}
else
{
powerStatus = true;
testRemote.DisplayMessage("TV On, Your Channel is 3 and the Volume is 5");
}
return powerStatus;
}
public static bool PowerOff(bool powerStatus)
{
if (powerStatus == false)
{
testRemote.DisplayMessage("TV already off");
}
else
{
powerStatus = false;
testRemote.DisplayMessage("TV is now off");
}
return powerStatus;
}
public static int VolumeUp(bool powerStat, int vol)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (vol >= 10)
{
testRemote.DisplayMessage("TV is already on Maximum Volume.");
}
else
{
vol++;
if (vol == 10)
{
testRemote.DisplayMessage("Maximum Volume.");
}
}
}
return vol;
}
public static int VolumeDown(bool powerStat, int vol)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (vol <= 0)
{
testRemote.DisplayMessage("Sound Muted");
}
else
{
vol--;
if (vol == 0)
{
testRemote.DisplayMessage("Sound Muted");
}
}
}
return vol;
}
public static int ChannelUp(bool powerStat, int channelNo)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (channelNo < 99)
{
channelNo++;
}
else
{
channelNo = 2;
}
Console.WriteLine("Channel " + channelNo.ToString());
}
return channelNo;
}
public static int ChannelDown(bool powerStat, int channelNo)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (channelNo == 2)
{
channelNo = 99;
}
else
{
channelNo--;
}
Console.WriteLine("Channel " + channelNo.ToString());
}
return channelNo;
}
public static String SmartMenu(bool powerStat, String md)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
testRemote.DisplayMessage("Smart Menu On");
md = "TV";
}
return md;
}
public static String SetSettings(bool powerStat, String md)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
testRemote.DisplayMessage("Settings On");
md = "Settings";
}
return md;
}
public static void DisplayMessage(String msg)
{
Console.WriteLine(msg);
}
public static void Banner()
{
Console.WriteLine("Welcome to TV Remote Control");
Console.WriteLine("Please enter your selection");
Console.WriteLine("Power On - turns on your TV");
Console.WriteLine("Power Off - turns off your TV");
Console.WriteLine("Increase volume - turns up the volume");
Console.WriteLine("Decrease volume - turn down the volume");
Console.WriteLine("Channel Up - increments the channel");
Console.WriteLine("Channel Down - decrements the channel");
Console.WriteLine("Smart Menu");
Console.WriteLine("Settings");
Console.WriteLine();
Console.WriteLine("Please enter your selection");
}
public static void Main(String[] args)
{
bool powerOn = false;
int channel = 3;
int volume = 5;
string mode = "TV";
string choice = "Turn On";
string c = Console.ReadLine();
while (choice.ToLower().Equals("Exit".ToLower()) != true)
{
if (choice.ToLower().Equals("Power On".ToLower()) == true)
{
powerOn = testRemote.PowerOn(powerOn);
}
if (choice.ToLower().Equals("Power Off".ToLower()) == true)
{
powerOn = testRemote.PowerOff(powerOn);
}
if (choice.ToLower().Equals("Increase volume".ToLower()) == true)
{
volume = testRemote.VolumeUp(powerOn, volume);
}
if (choice.ToLower().Equals("Decrease volume".ToLower()) == true)
{
volume = testRemote.VolumeDown(powerOn, volume);
}
if (choice.ToLower().Equals("Channel Up".ToLower()) == true)
{
channel = testRemote.ChannelUp(powerOn, channel);
}
if (choice.ToLower().Equals("Channel Down".ToLower()) == true)
{
channel = testRemote.ChannelDown(powerOn, channel);
}
if (choice.ToLower().Equals("Mode TV".ToLower()) == true)
{
mode = testRemote.SmartMenu(powerOn, mode);
}
if (choice.ToLower().Equals("Mode DVD".ToLower()) == true)
{
mode = testRemote.SetSettings(powerOn, mode);
}
Console.WriteLine();
Console.WriteLine();
choice = Console.ReadLine();
}
Console.WriteLine("Thank you for the Remote Controller");
Console.ReadLine();
}
}
Since the question is not clear i slightly modified your code, it compiles and runs BUT needs a lot of refactor.
Here is the working code.
using System;
namespace TvRemote
{
public class testRemote
{
public static bool PowerOn(bool powerStatus)
{
if (powerStatus == true)
{
testRemote.DisplayMessage("TV already on");
}
else
{
powerStatus = true;
testRemote.DisplayMessage("TV On, Your Channel is 3 and the Volume is 5");
}
return powerStatus;
}
public static bool PowerOff(bool powerStatus)
{
if (powerStatus == false)
{
testRemote.DisplayMessage("TV already off");
}
else
{
powerStatus = false;
testRemote.DisplayMessage("TV is now off");
}
return powerStatus;
}
public static int VolumeUp(bool powerStat, int vol)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (vol >= 10)
{
testRemote.DisplayMessage("TV is already on Maximum Volume.");
}
else
{
vol++;
if (vol == 10)
{
testRemote.DisplayMessage("Maximum Volume.");
}
}
}
return vol;
}
public static int VolumeDown(bool powerStat, int vol)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (vol <= 0)
{
testRemote.DisplayMessage("Sound Muted");
}
else
{
vol--;
if (vol == 0)
{
testRemote.DisplayMessage("Sound Muted");
}
}
}
return vol;
}
public static int ChannelUp(bool powerStat, int channelNo)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (channelNo < 99)
{
channelNo++;
}
else
{
channelNo = 2;
}
Console.WriteLine("Channel " + channelNo.ToString());
}
return channelNo;
}
public static int ChannelDown(bool powerStat, int channelNo)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (channelNo == 2)
{
channelNo = 99;
}
else
{
channelNo--;
}
Console.WriteLine("Channel " + channelNo.ToString());
}
return channelNo;
}
public static String SmartMenu(bool powerStat, String md)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
testRemote.DisplayMessage("Smart Menu On");
md = "TV";
}
return md;
}
public static String SetSettings(bool powerStat, String md)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
testRemote.DisplayMessage("Settings On");
md = "Settings";
}
return md;
}
public static void DisplayMessage(String msg)
{
Console.WriteLine(msg);
}
public static void Banner()
{
Console.WriteLine("Welcome to TV Remote Control");
Console.WriteLine("Please enter your selection");
Console.WriteLine("Power On - turns on your TV");
Console.WriteLine("Power Off - turns off your TV");
Console.WriteLine("Increase volume - turns up the volume");
Console.WriteLine("Decrease volume - turn down the volume");
Console.WriteLine("Channel Up - increments the channel");
Console.WriteLine("Channel Down - decrements the channel");
Console.WriteLine("Smart Menu");
Console.WriteLine("Settings");
Console.WriteLine();
Console.WriteLine("Please enter your selection");
}
public static void Main(String[] args)
{
bool powerOn = false;
int channel = 3;
int volume = 5;
string mode = "TV";
//string choice = "Turn On"; //THIS MUST BE Power On if you want to power on the tv as soon as the app is launched
Banner();
string choice = Console.ReadLine();
while (!choice.ToLower().Equals("Exit".ToLower()))
{
if (choice.ToLower().Equals("Power On".ToLower()) == true)
{
powerOn = testRemote.PowerOn(powerOn);
}
if (choice.ToLower().Equals("Power Off".ToLower()) == true)
{
powerOn = testRemote.PowerOff(powerOn);
}
if (choice.ToLower().Equals("Increase volume".ToLower()) == true)
{
volume = testRemote.VolumeUp(powerOn, volume);
}
if (choice.ToLower().Equals("Decrease volume".ToLower()) == true)
{
volume = testRemote.VolumeDown(powerOn, volume);
}
if (choice.ToLower().Equals("Channel Up".ToLower()) == true)
{
channel = testRemote.ChannelUp(powerOn, channel);
}
if (choice.ToLower().Equals("Channel Down".ToLower()) == true)
{
channel = testRemote.ChannelDown(powerOn, channel);
}
if (choice.ToLower().Equals("Mode TV".ToLower()) == true)
{
mode = testRemote.SmartMenu(powerOn, mode);
}
if (choice.ToLower().Equals("Mode DVD".ToLower()) == true)
{
mode = testRemote.SetSettings(powerOn, mode);
}
Console.WriteLine();
Console.WriteLine();
choice = Console.ReadLine();
}
Console.WriteLine("Thank you for the Remote Controller");
Console.ReadLine();
}
}
}
My program gives the user the option to serialize a certain list List<Position>ListPosition that stores the data from the class Position. It does serialize pretty well and it sorta looks like the following
{
"PosZ": 0,
"PosX": 749,
"PosY": 208,
"Agent": {
"IsEdgeTree": false,
"ThisTreesCreator": null,
"Type": 0,
"Colour": "Green",
"Dimension": 25
}
},
{
"PosZ": 0,
"PosX": 724,
"PosY": 183,
"Agent": {
"IsEdgeTree": false,
"ThisTreesCreator": {
"IsEdgeTree": false,
"Position": {
"PosZ": 0,
"PosX": 749,
"PosY": 208
},
"ThisTreesCreator": null,
"Type": 0,
"Colour": "Green",
"Dimension": 25
},
"Type": 0,
"Colour": "Green",
"Dimension": 25
}
},
These are just a few examples.
The bit that is giving me problems is when I deserialize it.
When I inspect the bit of code that converts it JsonConvert.DeserializeObject<List<Position>>(JsonString);, everything reads fine but, when I equal it to the List I am trying to dump the data to AKA the same list the serialized data comes from but empty, the data doesn't load and I'm left with the correct structure but no values.
Values not showing up
To Deserialize, I call the following method from another Windows Forms:
public static void Deserialize()
{
if (Directory.Exists("Serialized"))
{
var FileName = "Serialized/PositionsSerialized_4.json";
var JsonString = File.ReadAllText(FileName);
ListPositions = JsonConvert.DeserializeObject<List<Position>>(JsonString);
}
else
MessageBox.Show("There's no directory");
}
I would really appreciate some help. If more information is needed, be sure to request it in the comments.
Thank you for your time.
public class Position
{
public static int MaxX { get; private set; }
public static int MaxY { get; private set; }
public static List<Position> ListPositions { get; private set; }
public static List<Position> ListTreePositions {
get
{
return ListPositions.Where(w => w.Agent?.Type == AgentType.Tree).ToList();
}
}
public static List<Position> ListDronePositions
{
get
{
return ListPositions.Where(w => w.Agent?.Type == AgentType.Drone).ToList();
}
}
public int PosX { get; private set; }
public int PosY { get; private set; }
public int PosZ;
private static object services;
public Agent Agent { get; private set; }
public Position()
{
ListPositions = new List<Position>();
}
public static void SetMaxValues(int maxX, int maxY)
{
MaxX = maxX;
MaxY = maxY;
}
public void FillNeighbours(int posX, int posY, int dim)
{
for (int i = 0; i < dim; i++)
{
for (int y = 0; y < dim; y++)
{
new Position(posX - (dim - y), posY - (dim - i), Agent);
}
}
}
public static Position CreateNewRandomPosition()
{
Random rnd = new Random();
int rndX;
int rndY;
Position position = null;
while (position == null)
{
rndX = rnd.Next(MaxX - 100);
rndY = rnd.Next(MaxY - 100);
position = CreatePosition(rndX, rndY);
}
return position;
}
public static Bitmap ExportBitmap()
{
return ExportBitmap(0, 0, MaxX, MaxY, ListPositions);
}
public static Bitmap ExportBitmap(int posX, int posY, int maxX, int maxY)
{
var listPositions = ListPositions.Where(w => (w.Agent != null) && (w.PosX >= posX && w.PosX <= maxX) && (w.PosY >= posY && w.PosY <= maxY)).ToList();
return ExportBitmap(posX, posY, maxX, maxY, listPositions);
}
public static Bitmap ExportBitmap(int posX, int posY, int maxX, int maxY, AgentType agentType)
{
var listPositions = ListPositions.Where(w => (w.Agent.Type == agentType) && (w.PosX >= posX && w.PosX <= maxX) && (w.PosY >= posY && w.PosY <= maxY)).ToList();
return ExportBitmap(posX, posY, maxX, maxY, listPositions);
}
public static Bitmap ExportBitmap(int posX, int posY, int maxX, int maxY, AgentType[] agentType)
{
var listPositions = ListPositions.Where(w => (agentType.Contains(w.Agent.Type)) && (w.PosX >= posX && w.PosX <= maxX) && (w.PosY >= posY && w.PosY <= maxY)).ToList();
return ExportBitmap(posX, posY, maxX, maxY, listPositions);
}
private static Bitmap ExportBitmap(int posX, int posY, int maxX, int maxY, List<Position> positions)
{
Bitmap bmp = new Bitmap(maxX - posX, maxY - posY);
if (Agent.Sprites.Count() == 0)
{
Agent.LoadSprites();
}
Graphics g = Graphics.FromImage(bmp);
foreach (var item in positions)
{
var SpriteWidth = Agent.Sprites[item.Agent.Type].Width / 2;
var SpriteHeight = Agent.Sprites[item.Agent.Type].Height / 2;
g.DrawImage(Agent.Sprites[item.Agent.Type], new Point(item.PosX - SpriteWidth - posX, item.PosY - SpriteHeight - posY));
}
if (!Directory.Exists("Photos"))
{
Directory.CreateDirectory("Photos");
}
int count = Directory.GetFiles("Photos", "*").Length;
bmp.Save("Photos\\Img" + count + 1 + ".png", System.Drawing.Imaging.ImageFormat.Png);
return bmp;
}
public Position(int poxX, int poxY)
{
PosX = poxX;
PosY = poxY;
if (Agent != null)
ListPositions.Add(this);
}
public Position(int posX, int posY, Agent agent)
{
PosX = posX;
PosY = posY;
Agent = agent;
if (Agent != null)
ListPositions.Add(this);
}
public void AssociateAgent(Agent agent)
{
Agent = agent;
if (Agent != null)
ListPositions.Add(this);
}
public static bool CheckPositionIsValid(int poxX, int poxY)
{
int? NullableMaxX = MaxX;
int? NullableMaxY = MaxY;
var posXValid = poxX > 0 && (poxX <= MaxX || NullableMaxX == null); //verifies if posX is within the boundries of the premises
var posYValid = poxY > 0 && (poxY <= MaxY || NullableMaxY == null); //verifies if posY is within the boundries of the premises
return posXValid && posYValid; //returns if they are both valid
}
public static Position Find(int poxX, int poxY)
{
return ListPositions.Find(f => f.PosX == poxX && f.PosY == poxY) ?? null;
}
public static Position CreatePosition(int poxX, int poxY)
{
if (Find(poxX, poxY) == null)
if (CheckPositionIsValid(poxX, poxY))
return new Position(poxX, poxY);
else
return null;
else
return null;
}
public Dictionary<int, Position> ListNeighbourPositions(int dim = 1)
{
Dictionary<int, Position> NeighbourList = new Dictionary<int, Position>();
for (int i = 1; i < 9; i++)
{
if (i != 5)
{
var position = FindNeighbour(i, dim);
if (position != null)
NeighbourList.Add(i, position);
}
}
return NeighbourList;
}
public Position FindNeighbour(int neighbourPos, int dim)
{
var position = FindNeighbourbyPosition(neighbourPos, dim);
return Find(position.Item1, position.Item2);
}
public Tuple<int, int> FindNeighbourbyPosition(int neighbourPos, int dim = 1)
{
int neighbourPosX;
int neighbourPosY;
switch (neighbourPos)
{
case 1:
neighbourPosX = PosX - dim;
neighbourPosY = PosY - dim;
break;
case 2:
neighbourPosX = PosX;
neighbourPosY = PosY - dim;
break;
case 3:
neighbourPosX = PosX + dim;
neighbourPosY = PosY - dim;
break;
case 4:
neighbourPosX = PosX - dim;
neighbourPosY = PosY;
break;
case 6:
neighbourPosX = PosX + dim;
neighbourPosY = PosY;
break;
case 7:
neighbourPosX = PosX - dim;
neighbourPosY = PosY + dim;
break;
case 8:
neighbourPosX = PosX;
neighbourPosY = PosY + dim;
break;
case 9:
neighbourPosX = PosX + dim;
neighbourPosY = PosY + dim;
break;
default:
return null;
}
return new Tuple<int, int>(neighbourPosX, neighbourPosY);
}
public void UpdatePosition(int newX, int newY)
{
PosX = newX;
PosY = newY;
}
public static void Serialize()
{
if (!Directory.Exists("Serialized"))
{
Directory.CreateDirectory("Serialized");
}
int count = Directory.GetFiles("Serialized", "*").Length;
string fileName = "Serialized/PositionsSerialized_" + count + ".json";
string jsonString = JsonConvert.SerializeObject(ListPositions, Formatting.Indented, new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
File.WriteAllText(fileName, jsonString);
}
public static void Deserialize()
{
if (Directory.Exists("Serialized"))
{
var FileName = "Serialized/PositionsSerialized_4.json";
var JsonString = File.ReadAllText(FileName);
ListPositions = JsonConvert.DeserializeObject<List<Position>>(JsonString);
}
else
MessageBox.Show("There's no directory");
}
}
The reason of your problem is because you defined setters as private...
public static int MaxX { get; private set; }
public static int MaxY { get; private set; }
public int PosX { get; private set; }
public int PosY { get; private set; }
it should be...
public static int MaxX { get; set; }
public static int MaxY { get; set; }
public int PosX { get; set; }
public int PosY { get; set; }
I am having a problem about structures. I am trying to calculate quadrengles parameter, area and whether it is square or not but code doesn't go to if else part of islem();. This is my homework about struct.
using System;
public struct Str
{
private double val;
public double Value
{
get { return val; }
set { val = value; }
}
public double Oku()
{
return double.Parse(Console.ReadLine());
}
}
public struct Dörtgen
{
Str ak;
Str bk;
public Str Ake
{
get { return ak; }
set { ak = value; }
}
public Str Bke
{
get { return bk; }
set { bk = value; }
}
public void Dörtgen1()
{
Str rct = new Str();
Console.WriteLine("\nenter sides a and be of the square: ");
Console.Write("A side: ");
ak.Value = rct.Oku();
Console.Write("B side: ");
bk.Value = rct.Oku();
}
public void İslem()
{
Console.WriteLine("parameter: {0}", (Ake.Value + Bke.Value) * 2);
Console.WriteLine("area: {0}\n", Ake.Value * Bke.Value);
if (Ake.Value == Bke.Value)
{
Console.WriteLine("this is a square");
}
else if (Ake.Value == Bke.Value)
{
Console.WriteLine("this is not a square");
}
}
}
public class Program
{
static void Main()
{
var drg = new Dörtgen();
drg.Dörtgen1();
Console.WriteLine();
Console.WriteLine("parameter and area");
drg.İslem();
}
}
if (Ake.Value == Bke.Value)
{
Console.WriteLine("this is a square");
}
else if (Ake.Value == Bke.Value)
{
Console.WriteLine("this is not a square");
}
Should be:
// Sides are equal: it's a square
if (Ake.Value == Bke.Value)
{
Console.WriteLine("this is a square");
}
// didn't enter the "square" branch, so it's not a square
else
{
Console.WriteLine("this is not a square");
}
Explanation: Besides the fact that you wrote Ake.Value == Bke.Value in both if and else if, you don't actually need to check anything if the first if is false, you can just go to the else branch.
I have a simple inventory application which is a program which you can add, view and delete the product. Currently I had already finished the add function and view function but left only the delete function which I am unsure of. ( Main program case 3)
class Inventory
{
Product []items;
int maxSize;
int size;
public Inventory(int in_maxSize)
{
maxSize = in_maxSize;
size = 0;
items = new Product[maxSize];
}
public bool AddProduct(Product in_Product)
{
if(getSize()<maxSize)
{
items[size] = in_Product;
size++;
return true;
}
else
{
return false;
}
}
public int getSize()
{
return size;
}
public Product getProduct(int index)
{
return items[index];
}
}
}
here is my product class:
class Product
{
private string name;
private int itemNumber;
private int unitsInStock;
private double price;
private double value;
public Product()
{
}
public Product(string in_name, int in_itemNumber, int in_unitsInStock, double in_price)
{
name = in_name;
itemNumber = in_itemNumber;
unitsInStock = in_unitsInStock;
price = in_price;
}
public double getValueOfInventory()
{
value = unitsInStock * price;
return this.value;
}
public int getItemNumber()
{
return this.itemNumber;
}
public string getName()
{
return this.name;
}
public int getUnitsInStock()
{
return this.unitsInStock;
}
public double getPrice()
{
return this.price;
}
public void setItemNumber(int in_itemNumber)
{
itemNumber = in_itemNumber;
}
public void setName(string in_name)
{
name = in_name;
}
public void setUnitsInStock(int in_unitsInStock)
{
unitsInStock = in_unitsInStock;
}
public void setPrice(double in_price)
{
price = in_price;
}
}
}
Here is my main program:
class Program
{
static void Main(string[] args)
{
Inventory myInventory = new Inventory(100);
Product myProduct = new Product();
myProduct.setItemNumber(1000);
myProduct.setName("Pen");
myProduct.setPrice(1.25);
myProduct.setUnitsInStock(50);
myInventory.AddProduct(myProduct);
Product myProduct1 = new Product("Paper", 2000, 5000, 12.85);
myInventory.AddProduct(myProduct1);
Product tempProduct;
int x = 0;
do
{
Console.WriteLine("1.Add product");
Console.WriteLine("2.View product");
Console.WriteLine("3.Delete product");
Console.WriteLine("4.Exit the Application");
Console.WriteLine("------------------");
x = Convert.ToInt32(Console.ReadLine());
switch (x)
{
case 1:
Console.Write("Item number\t\t:");
int a=Convert.ToInt32(Console.ReadLine());
Console.Write("Name\t\t\t:");
string b=Convert.ToString(Console.ReadLine());
Console.Write("Price\t\t\t:");
double c=Convert.ToDouble(Console.ReadLine());
Console.Write("Units in stocks\t\t:");
int d=Convert.ToInt32(Console.ReadLine());
Product myProduct2 = new Product(b,a,d,c);
myInventory.AddProduct(myProduct2);
// Product myProduct1 = new Product("Paper", 2000, 5000, 12.85);
// myInventory.AddProduct(myProduct1);
/*Console.Write("Item number\t\t:");
ItemNo = Convert.ToInt32(Console.ReadLine());
Console.Write("Name\t\t\t:");
Name = Convert.ToString(Console.ReadLine());
Console.Write("Price\t\t\t:");
Price = Convert.ToDouble(Console.ReadLine());
Console.Write("Units in stocks\t\t:");
UnitsInStocks = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("------------------");*/
break;
case 2:
for (int i = 0; i < myInventory.getSize(); i++)
{
tempProduct = myInventory.getProduct(i);
Console.WriteLine("Item number\t\t:" + tempProduct.getItemNumber());
Console.WriteLine("Name\t\t\t:" + tempProduct.getName());
Console.WriteLine("Price\t\t\t:" + tempProduct.getPrice());
Console.WriteLine("Units in stocks\t\t:" + tempProduct.getUnitsInStock());
Console.WriteLine("------------------");
}
break;
case 3:
int j;
Console.WriteLine("Please enter the item id for the items that you want to delete");
j = Convert.ToInt32(Console.ReadLine());
if (j == a)
{
break;
case 4:
Environment.Exit(0);
break;
default:
break;
}
}
while (x != 4);
}
}
}
In my main program, i left case 3 undone as that is the delete function part,
How can I accomplish this?
This is the simple way. Replace your array with a List of products:
class Inventory
{
List<Product> items;
int maxSize;
public Inventory(int in_maxSize)
{
maxSize = in_maxSize;
items = new List<Product>();
}
public bool AddProduct(Product in_Product)
{
if(items.Count < maxSize)
{
items.Add(in_Product);
return true;
}
else
{
return false;
}
}
public Product getProduct(int index)
{
return items[index];
}
public void removeProduct(int index)
{
items.removeAt(index);
}
}
In your switch call removeProduct method to delete the product at position that you pass.
Can I add values to an instance of an object after I have used the constructor?
For instance I have this code. I have to make a list of objects which require a number n, and the time (which are recieved as arguments). The problem is that the time can be anywhere so I can't use it in a constructor.
public List<IAction> Dispatch(string[] arg)
{
int time;
int i = 0;
int j = 0;
List<IAction> t = new List<IAction>(10);
do
{
if (int.Parse(arg[j]) >= 0 && int.Parse(arg[j]) <= 20)
{
t.Add(new ComputeParam(int.Parse(arg[j])));
i++;
j++;
}
else
{
if (arg[i][0] == '/' && arg[i][1] == 't')
{
Options opt = new Options();
j++;
time=opt.Option(arg[i]); //sets the time 0,1000 or 2000
}
}
} while (i != arg.Length);
return t;
}
After finishing making the list can I do something like:
for(int i=0; i<=t.Count; i++)
{
*add time to t[i]*
}
How do I do this?
Thanks in advance!
Edit :
here is the ComputeParam class
public class ComputeParam : IAction
{
int n;
int time;
public ComputeParam()
{
}
public ComputeParam(int n)
{
this.n = n;
}
public void run()
{
Factorial Fact = new Factorial();
Fact.Progression += new Factorial.ProgressEventHandler(Progress);
Console.WriteLine(" ");
Console.Write("\n" + "Partial results : ");
Console.CursorLeft = 35;
Console.Write("Progress : ");
int Result = Fact.CalculateFactorial(n, time);
Console.WriteLine(" ");
Console.WriteLine("The factorial of " + n + " is : " + Result);
Console.WriteLine("Press Enter to continue...");
Console.CursorTop -= 2;
Console.CursorLeft = 0;
Console.ReadLine();
}
public void Progress(ProgressEventArgs e)
{
int result = e.getPartialResult;
int stack_value = e.getValue;
double max = System.Convert.ToDouble(n);
System.Convert.ToDouble(stack_value);
double percent = (stack_value / max) * 100;
Console.CursorLeft = 18;
Console.Write(result + " ");
Console.CursorLeft = 46;
Console.Write(System.Convert.ToInt32(percent) + "% ");
}
}
If the object has a public property, I don't see why not.
Edit: Looks like you need to add a public property to your class. Also note, given that there is a public constructor that takes 0 params, you should also add a property for n.
public class ComputeParam : IAction
{
int _n;
int _time;
public ComputeParam()
{
}
public ComputeParam(int n)
{
this._n = n;
}
public int Time
{
get { return this._time; }
set { this._time = value; }
}
public int N
{
get { return this._n; }
set { this._n = value; }
}
for(int i = 0; i < t.Count; i++)
{
((ComputeParam)t[i]).Time = 6;
}