When i call ReadList function it dosent print the elements,what i am doing wrong?i tried even with normal list.What i want to do is if i create 2 accounts by CreateAccount function, i want to print them both through ReadList.
namespace Bank
{
class Program
{
static void Main()
{
int option;
do
{
Menu1 menu1 = new Menu1();
Account account = new Account();
option = menu1.CallMenu1();
if (option == 1)
{
account.CreateAccount();
}else if (option == 2) {
account.ReadList();
break;
}
else
{
break;
}
} while (true);
}
}
class Account
{
int AccountNumber { get; set; }
string Name { get; set; }
float Balance { get; set; }
public void CreateAccount()
{
int AccountNumberInput;
string NameInput;
float BalanceInput;
ArrayList list = new ArrayList();
Console.WriteLine("put id");
AccountNumberInput = int.Parse(Console.ReadLine());
Console.WriteLine("type name");
NameInput =Console.ReadLine();
Console.WriteLine("type balance");
BalanceInput = float.Parse(Console.ReadLine());
list.Add(AccountNumberInput);
list.Add(NameInput);
list.Add(BalanceInput);
}
public void ReadList()
{
ArrayList list = new ArrayList();
foreach (string c in list)
{
Console.WriteLine(c);
}
}
}
}
Your CreateAccount method does this:
Creates a new list
Populates the list
Does nothing with the list
Your ReadList method does this:
Creates a new (empty) list
Prints the contents of the list
The list created in CreateAccount() is never communicated outside the method - how do you expect the ReadList() method to know about it?
The simplest change would be to make CreateAccount() return the list it creates, then change ReadList to accept an ArrayList as a parameter. You'd change your Main method to store the result of CreateAccount in a local variable, then pass it to ReadList when it calls that.
However, beyond that:
I would avoid using ArrayList in any new code. It was superceded many, many years ago by List<T>.
Your CreateAccount method should surely do what it says: create an account. It should probably be a static method returning an Account... then your ReadList method could just be a PrintDetails instance method without any parameters, because you would call it on the instance returned by CreateAccount.
You should consider what you want to do if you someone tries to print the account before creating it...
Because your class is wrong. You are initialising your list inside one of your methods. Once your method completes execution, everything inside it is unloaded from the memory.
For this to work, you have to add a field/property to the class itself that contains the data and can be used by all the methods of the class
class Account
{
int AccountNumber { get; set; }
string Name { get; set; }
float Balance { get; set; }
//added this line
private ArrayList list {get;set;}
public void CreateAccount()
{
int AccountNumberInput;
string NameInput;
float BalanceInput;
//notice this
list = new ArrayList();
Console.WriteLine("put id");
AccountNumberInput = int.Parse(Console.ReadLine());
Console.WriteLine("type name");
NameInput =Console.ReadLine();
Console.WriteLine("type balance");
BalanceInput = float.Parse(Console.ReadLine());
list.Add(AccountNumberInput);
list.Add(NameInput);
list.Add(BalanceInput);
}
public void ReadList()
{
//removed ArrayList list = new ArrayList();
foreach (string c in list)
{
Console.WriteLine(c);
}
}
}
Related
I'm currently learning C# and have assigned myself to make a program to help me understand OOP which essentially takes in values and assigns them to variables. The program takes in information about football players; the name, last name, position, and shirt number.
I'm trying to use getters and setters to ensure that a shirt number can only be used once. So i've set a list up that stores all the shirt numbers that are being used. The problem i'm having is: the list keeps getting reset and I have no idea why. After one value has been added, by the time the next one gets added, the list is empty again. This makes my if statement in the setter not work as the list does not contain any values.
Im sure this is a rookie error and should be shouting at me, but Im new to this language and am not really sure on all the ins and outs of it.
I haven't really tried much, and I cant find anything online as this seems to be a specific error that im having. I don't know enough about the language to properly troubleshoot this, and what I do know about the language tells me this should work.
namespace RandomObject
{
class Program
{
static void Main(string[] args)
{
Player player1 = new Player("Lucas", "Torreira", "Defensive Midfielder", 11);
Player player2 = new Player("Alexandre", "Lacazette", "Striker", 9);
Player player3 = new Player("Pierre-Emerick", "Aubameyang", "Striker", 14);
Player player4 = new Player();
Console.Write("Please enter new players first name: ");
player4.Name = Console.ReadLine();
Console.Write("Please enter new players last name: ");
player4.LastName = Console.ReadLine();
Console.Write("Please enter new players position: ");
player4.Position = Console.ReadLine();
Console.Write("Please enter new players shirt number: ");
player4.ShirtNo = Convert.ToInt32(Console.ReadLine());
player1.PrintPlayerInfo();
player2.PrintPlayerInfo();
player3.PrintPlayerInfo();
player4.PrintPlayerInfo();
Console.ReadKey();
}
}
}
class Player
{
private List<int> shirtNumbers = new List<int>();
private int _shirtNo;
public void PrintPlayerInfo() //<access modifier> <return type> <method name>(parameters)
{
Console.WriteLine("Player: {0} {1}", Name, LastName);
Console.WriteLine("Position: {0}", Position);
Console.WriteLine("Shirt No.: {0}\n", _shirtNo);
}
public Player()
{
Name = string.Empty;
LastName = string.Empty;
Position = string.Empty;
_shirtNo = 0;
}
public Player(string name, string lastName, string position, int shirtNo)
{
Name = name;
LastName = lastName;
Position = position;
_shirtNo = shirtNo;
AddToList(_shirtNo);
}
private void AddToList(int newNumber)
{
shirtNumbers.Add(newNumber);
Console.WriteLine(shirtNumbers[0]);
}
public string Name { get; set; }
public string LastName { get; set; }
public string Position { get; set; }
public int ShirtNo
{
get { return _shirtNo; }
set
{
if (shirtNumbers.Contains(value) == false)
{
_shirtNo = value;
}
else
{
_shirtNo = 0;
}
}
}
}
}
In my main method I declare 3 instances of the class, with shirt numbers 11, 9, and 14. So when it comes to inputting one into the console using readlines and such, if I were to enter 14, the shirt number should be set to 0. However if I enter 10, it should be set to 10.
The Player class now does two things: it holds information about one player, and it contains a list of shirt numbers for all players. One of those two doesn't belong there.
The private List<int> shirtNumbers = new List<int>(); is an instance variable, meaning each player has its own list of shirt numbers. So if you assign a shirt to player X, the list in player Y's instance has no notion of this, enabling you to assign shirt N to both player X and Y.
Sure, you could fix this by declaring the list to be static, but that's just bad design; the Player class needs to know about one player, not all of them.
So instead keep this shirt number check outside your player class. Declare the shirt list before the player list, and modify your code accordingly.
You should have a static list of numbers. Otherwise every player has its own list of valid numbers.
class Player
{
private static List<int> shirtNumbers = new List<int>();
private int _shirtNo;
}
This way you have a single list that all your player share.
You are using the AddToList method on your constructor to add the shirtlist number which is correctly but when you are defining ShirtNo setter you are not adding to the list
Fix :
public int ShirtNo
{
get { return _shirtNo; }
set
{
if (shirtNumbers.Contains(value) == false)
{
_shirtNo = value;
AddToList(value)
}
else
{
_shirtNo = 0;
}
}
}
i copied your code to debug in my local machine. Few changes that needs to be done to your
1.The shirtNumbers list has to be declared static , if not for every instance of player class will have List (private static List shirtNumbers = new List();)
You are assigning values to the variable directly and not to the property in both the constructors.(getter setter is called property in C#).Hence the if condition inside setter wont be called.
class Player
{
private static List<int> shirtNumbers = new List<int>();
private int _shirtNo;
public void PrintPlayerInfo()
{
Console.WriteLine("Player: {0} {1}", Name, LastName);
Console.WriteLine("Position: {0}", Position);
Console.WriteLine("Shirt No.: {0}\n", _shirtNo);
}
public Player()
{
Name = string.Empty;
LastName = string.Empty;
Position = string.Empty;
ShirtNo = 0;
}
public Player(string name, string lastName, string position, int shirtNo)
{
Name = name;
LastName = lastName;
Position = position;
ShirtNo = shirtNo;
AddToList(_shirtNo);
}
private void AddToList(int newNumber)
{
shirtNumbers.Add(newNumber);
Console.WriteLine(shirtNumbers[0]);
}
public string Name { get; set; }
public string LastName { get; set; }
public string Position { get; set; }
public int ShirtNo
{
get { return _shirtNo; }
set
{
if (shirtNumbers.Contains(value) == false)
{
_shirtNo = value;
}
else
{
_shirtNo = 0;
}
}
}
}
A quick question on OOP. I am using a list together with a class and class constructor. So I use the class constructor to define the data set and then add each record to my list as the user creates them.
My questions is once the data is in the list and say I want to alter something is it good practice to find the record, create an instance using that record and then use my class methods to do whatever needs doing - and then put it back in the list?
For example below I have my class with constructor. Lets say I only want the system to release strCode if the Privacy field is set to public. Now just using Instances I would use for example Console.WriteLine(whateverproduct.ProductCode) but if the record is already in a list do i take it out of the list - create an instance and then use this method?
class Product
{
private String strCode;
private Double dblCost;
private Double dblNet;
private String strPrivacy;
public Product(String _strCode, Double _dblCost, Double _dblNet, String _strPrivacy)
{
strCode = _strCode;
dblCost = _dblCost;
dblNet = _dblNet;
strPrivacy = _strPrivacy;
}
public string ProductCode
{
get
{
if (strPrivacy == "Public")
{
return strCode;
}
else
{
return "Product Private Can't release code";
}
}
}
Lets say we have the following:
public class Test
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Amount { get; set; }
private string _test = "Some constant value at this point";
public string GetTest()
{
return _test;
}
public void SetTest()
{
//Nothing happens, you aren't allow to alter it.
//_test = "some constant 2";
}
}
public class Program
{
public static void Main(string[] args)
{
List<Test> listOfTest = new List<Test>()
{
new Test() {Id = 0, Name = "NumberOne", Amount = 1.0M},
new Test() {Id = 1, Name = "NumberTwo", Amount = 2.0M}
};
Test target = listOfTest.First(x => x.Id == 0);
Console.WriteLine(target.Name);
target.Name = "NumberOneUpdated";
Console.WriteLine(listOfTest.First(x => x.Id == 0).Name);
Console.WriteLine(listOfTest.First(x => x.Id == 0).GetTest());//This will alsways be "Some constant value at this point";
Console.ReadLine();
}
}
Technically you could do away with the SetTest method entirely. However, I included it to demonstrate, what it would look like, if you wanted to alter _test.
You don't want to ever create a new instance of a class, you already have an instance of. you can just alter the class where it is allowed by the author of the class, where you need to. And keep that class reference for as long as you need it. Once you are done, the reference will be garbage collected, once the program finds no active reference to your object(instance).
I am trying to practice OOP. I have a class called Cinema and interface called location. Location Interface has List type and when I am trying to add the location name, It is giving error. Any direction or suggestion will be great -
The error is: "The name 'cinema_location' does not exist in the current context."
namespace MOSS.Interfaces
{
interface loc
{
List<string> location { get; set;}
}
}
namespace MOSS
{
class Cinema : Interfaces.loc
{
List<string> cinema_location = new List<string>();
cinema_location.Add("location1");
cinema_location.Add("location2");
public List<string> location
{
get
{
return cinema_location;
}
set
{
cinema_location = value;
}
}
public void DisplayCinema()
{
string loc;
string Session;
for(int i = 0; i < cinema_location.Count; i++)
{
loc = cinema_location[i];
Console.WriteLine("Cinema Location: {0}", loc);
}
}
}
}
A code like this one
cinema_location.Add("location1");
cinema_location.Add("location2");
can't be put wherever you like. In particular, it has to be put in a method, could be a class constructor.
Try
public class Cinema
{
List<string> cinema_location = new List<string>();
public Cinema()
{
cinema_location.Add("location1");
cinema_location.Add("location2");
}
...
Your c cinema_location.Add(...)s have to be inside a method (you cannot execute code directly in class scope).
It seems like you want these names added at object creation, right? In that case you need a constructor and add thr method calls there:
class Cinema
{
List<string> cinema_locations = new List<string>();
public Cinema()
{
cinema_locations.Add("location1");
}
}
You need a constructor (https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constructors):
Public Cinema()
{
cinema_location.Add("location1");
cinema_location.Add("location2");
}
I need help on how to make a for loop. Then using the i value as both arrayList index numbers.
My directions say
-Create a loop that uses either the length of the ArrayList or the element to dictate the number of times the loop will run.
-Each time the loop runs, pull another element of the ArrayList and output it in a
meaningful fashion to the console.
static void Main(string[] args)
{
nameArrayLists();
}
public static void nameArrayLists() {
ArrayList teamLists = new ArrayList() {"Cloud 9"};
teamLists.Add("Fnatic");
teamLists.Add("SKT T1");
teamLists.Add("Flash Wolves");
teamLists.Add("EDG");
ArrayList region = new ArrayList() { "North America" };
region.Add("Europe");
region.Add("Korea");
region.Add("Taiwan");
region.Add("China");
So after this, how do I make a for loop using i as both arrayList index numbers? The end result should be like "Fnatic is in the Europe region, cloud 9 is the in north america region" etc.
If i understand correctly, you are looking for something like this:
if (teamLists.Count == region.Count)
{
for (int i = 0; i < teamLists.Count; i++)
{
Console.WriteLine("{0} is in the {1} region", teamLists[i], region[i]);
}
}
else
{
Console.WriteLine("Items in the collections are not matching");
}
Keep in mind: Both the list are in the same order. which means for any i the value at corresponding index should be matching.
There is a best option for you:
Create a simple class with two properties(more if needed), then an overrided ToString() method which is for displaying the text as you described. and then use a List as like the following;
Class definition:
public class TeamNRegion
{
public string TeamName { get; set; }
public string RegionName { get; set; }
public int Id { get; set; }
public override string ToString()
{
return String.Format("{0} is in the {1} region", this.TeamName, this.RegionName);
}
}
Then you can create the list of this class objects like this:
List<TeamNRegion> teamRegionList = new List<TeamNRegion>()
{
new TeamNRegion(){Id=1,TeamName="Fnatic",RegionName="Europe"},
new TeamNRegion(){Id=10,TeamName="SKT T1",RegionName="Korea"},
new TeamNRegion(){Id=11,TeamName="Flash Wolves",RegionName="Taiwan"},
new TeamNRegion(){Id=12,TeamName="EDG",RegionName="China"},
};
// Print the result like this
foreach (TeamNRegion team in teamRegionList)
{
Console.WriteLine(team.ToString());
}
I'm fairly new to C# and I have just learned about creating custom classes. The problem is, I can't figure out how to take the 40~65 instances of this class and put them in a list/array (whichever one I need) where I can locate and choose one based on an attribute defined in it.
Here's the class I have created right now:
public class Team
{
protected int teamNum;
protected double averageMatchPoints;
protected string location;
protected int matchesPlayed;
protected int matchesPending;
protected int blowouts;
//Team Number
public void SetNumber(int num)
{
teamNum = num;
}
public int GetNumber()
{
return teamNum;
}
//Average Points per match
public void AverageMatchPoints(double p)
{
averageMatchPoints = p;
}
public double GetAverageMatchPoints()
{
return averageMatchPoints;
}
//location information
public void SetLocation(string l)
{
location = l;
}
public string GetLocation()
{
return location;
}
//Number of Played Matches
public void PlayedMatches(int mat)
{
matchesPlayed = mat;
}
public int GetPlayedMatches()
{
return matchesPlayed;
}
//Number of matches pending (not played)
public void PendingMatches(int pen)
{
matchesPending = pen;
}
public int GetPendingMatches()
{
return matchesPending;
}
//Number of Blowouts (matches where the robot was disbaled for any number of reasons)
public void SetBlowouts(int b)
{
blowouts = b;
}
public int GetBlowouts()
{
return blowouts;
}
}
Now, if I had 40~65 of these teams competing at an event and I made an instance of this class for each one, how would I populate a combobox with each team number (teamNum) and then locate one specific team out of all the instances in the program by their team numbers?
I recommend a dictionary!
// Declared somewhere
private Dictionary<int, Team> _teamDictionary = new Dictionary<int, Team>();
.
.
.
//Initialization code - I assume you have gotten your teams from a database or somewhere?
foreach (var team in myTeamsList)
{
_teamDictionary.Add(team.teamNum, team);
}
.
.
.
// Later when you want to locate a team:
var team = _teamDictionary[selectedTeamNum];
Have you tried creating a List yet?
List<Team> Teams { get; set; }
You can then bind your combobox to the list/collection/IEnumerable of all the teams that you have. To initialize the teams up to 40/60 do the following?
for(int i = 0; i < 60; i++)
{
Team t = new Team();
t.Name = "Team 1";
t.TeamNumber = i + 1;
Teams.Add(t);
}
List<Team> allTheTeams = new List<Team>();
for(var i = 0; i < 65; i++){
allTheTeams.Add(new Team { teamNum = i });
}
And to get the team with number 34:
allTheTeams.FirstOrDefault(x => x.teamNum == 34);
Like this:
Add a constructor to your class that takes the teamnumber:
(this is the best solution if every team needs to have a number. So you can not forget to set the team number as you can not create an object of type team without setting the number in the constructor)
public class Team
{
protected int _teamNum;
public Team(int teamNum)
{
_teamNum = teamNum;
}
public int getTeamNum()
{
return _teamNum;
}
//more logic
}
Populate a dictionary, the comboBox and get a team for its number:
Dictionary<int, Team> dictionary = new Dictionary<int, Team>();
int teamNum = 1;
// Add your Teams to a dictionary (example)
dictionary.Add(teamNum ,new Team(teamNum++));
dictionary.Add(teamNum, new Team(teamNum++));
dictionary.Add(teamNum, new Team(teamNum++));
// Populate a comboBox
foreach(KeyValuePair<int,Team> kvp in dictionary)
{
comboBox1.Items.Add(kvp.Value.getTeamNum().ToString());
}
// get a team for a given teamNumer
int targetTeamNumber = 2;
if (dictionary.ContainsKey(targetTeamNumber))
{
Team team = dictionary[targetTeamNumber];
// do something with the team
}