how to print properties of object in list? - c#

i am a begginer in c# .
my problem is that i want to create a list of objects that i can add objects dynamically and then print their properties(i want to go to every object that i want and print only his properties).
i looked around the internet and didn't find a good answer that will help me understand how to to do it correctly.
i added a try...catch to understand the problem but the explantation i got is that i didn't add instance to print his properties even that i totaly did it.
i am really lost so any help would be appreciated.
my code :
class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using APPcLASS_2;
using System.Collections;
namespace EmployeesBooks
{
public class EMpLOYcLaSS
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int PhoneNumber { get; set; }
public string Adress { get; set; }
public int Days { get; set; }
public int Mounths { get; set; }
public int Years { get; set; }
}
}
main program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using APPcLASS_2;
using EmployeesBooks;
namespace EmployeesBooks
{
class Program
{
static void Main(string[] args)
{
EMpLOYcLaSS Employ = new EMpLOYcLaSS();
List<EMpLOYcLaSS> ListOfObjects = new List<EMpLOYcLaSS>();
string FirstNameVar, LastNameVar, AdressVar;
int PhoneNumberVar, DayVar, MounthVar, YearVar;
while(true)
{
Console.Clear();
Console.WriteLine("Enter your choise:");
Console.WriteLine("1-Add an employee");
Console.WriteLine("2-Earase employee");
Console.WriteLine("3-Show reports");
var choise=int.Parse(Console.ReadLine());
switch(choise)
{
case 1:
Console.WriteLine("Enter First Name:",Employ.FirstName);
FirstNameVar = Console.ReadLine();
Employ.FirstName = FirstNameVar;
Console.WriteLine("Enter Last Name:");
LastNameVar = Console.ReadLine();
Employ.LastName = LastNameVar;
Console.WriteLine("Enter Phone Number:");
PhoneNumberVar =int.Parse(Console.ReadLine());
Employ.PhoneNumber = PhoneNumberVar;
Console.WriteLine("Enter Address:");
AdressVar = Console.ReadLine();
Employ.Adress = AdressVar;
Console.WriteLine("Enter Birthday:");
Console.WriteLine("Day:");
DayVar =int.Parse(Console.ReadLine());
Employ.Days = DayVar;
Console.WriteLine("Mounth:");
MounthVar = int.Parse(Console.ReadLine());
Employ.Mounths = MounthVar;
Console.WriteLine("Year:");
YearVar = int.Parse(Console.ReadLine());
Employ.Years = YearVar;
ListOfObjects.Add(new EMpLOYcLaSS());
break;
case 3:
try
{
Console.WriteLine("enter a number of employee:(1,2,3,4...)");
var EmployeeNumberForPrinting = int.Parse(Console.ReadLine());
if (ListOfObjects[EmployeeNumberForPrinting] != null)
Console.WriteLine("{0}", ListOfObjects[EmployeeNumberForPrinting].FirstName.ToString());
else
Console.WriteLine("Don't Exist!");
Console.WriteLine("Press any key to proceed");
Console.ReadKey();
break;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
break;
}
}
}
}
}
}

Well first of all you don't add the employee into the list, you add a new one.
Change
ListOfObjects.Add(new EMpLOYcLaSS());
To
ListOfObjects.Add(Employ);
That will add the employee you created into the list, now to print each employee's name for example.
foreach(var e in ListOfObjects)
{
Console.WriteLine(e.FirstName + " " + e.LastName);
}
Obviously you can add more properties as you wish, this simply goes through all the objects and prints each of their names. Your code to print a predetermined employee should work now, just remove ToString() as it's already a string. Just a note, remember 0 is the first index in a list. I recommend for usability add one to EmployeeNumberForPrinting due to this, your decision.

Related

C# name doesnt exist in current context

Below is my main code the following code block is my book class. I am fairly new to c# and haven't encountered this error before. I am getting errors on line 39 and 48. Both are the printInformation() calls. The error is
the name 'printInformation' does not exist in the current context
I'm not sure what to do, I tried putting all the code from both the book class and the main class into a seperate file where all the code was together and it doesn't give an error.
Does this means there is something I need to do as far as the public and private classes used or is it something else. I have public getters and setters for the values title, author, price, and isbn.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the amount of books you have, followed by the number 1 or number 2 seperated by a space");
Console.Write("Enter 1 if you would like to sort the books by price in ascending order");
Console.WriteLine("Enter 2 if you would like to sort the books by title alphabetically.");
string number = Console.ReadLine();
string[] numberArray = number.Split(' ');
List<Book> bookList = new List<Book>();
// for the number entered input values
for (int i = 0; i < Convert.ToInt16(numberArray[0]); i++)
{
bookList.Add(new Book
{
Title = Console.ReadLine(),
Author = Console.ReadLine(),
Price = Convert.ToDouble(Console.ReadLine()),
ISBN = Console.ReadLine()
});
}
// sorting based on condition given
if (Convert.ToInt16(numberArray[1]) == 1)
{
var sortedList = from book in bookList orderby book.Price select book;
foreach (var book in sortedList)
{
printInformation(book.Title, book.Author, book.Price, book.ISBN);
}
}
else
{
var sortedList = from book in bookList orderby book.Title select book;
foreach (var book in sortedList)
{
printInformation(book.Title, book.Author, book.Price, book.ISBN);
}
}
// added this to hold the console window
Console.ReadLine();
}
}
}
Book class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public class Book
{
// private fields
private string title;
private string author;
private double price;
private string isbn;
public static void printInformation(string _title, string _author, double _price, string _isbn)
{
Console.WriteLine(_title + " written by " + _author + " is " + _price.ToString() + " dollars, with ISBN " + _isbn);
}
}
}
printInformation method is declared in the Book class as static, so you need to call it specifying the type name:
Book.printInformation(book.Title, book.Author, book.Price, book.ISBN);
Btw, you don't need this method, if you want to a string representation of a Book, a better way is to override ToString method in the Book class.

how to have a comma after each string but not in front

I have a problem with my class where it displays a comma before it displays the string and I cant find a way to take the comma out in the front and keep it in all the other places
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Carnival
{
class Player
{
public string Name { get; set; }
public double SpendingMoney { get; set; }
public string PrizesWon { get; set; }
//constructors
public Player( string n, double sp)
{
Name = n;
SpendingMoney = sp;
PrizesWon = "";
}
//methods
public string Play(GameBooth aGames)
{
string newPrize;
if (SpendingMoney >= aGames.Cost)
{
newPrize = aGames.Start();
//here is what I need to fix
PrizesWon = "," + newPrize + PrizesWon ;
return newPrize;
}
else
{
return "error no money fool";
}
}
}
}
here is the main code if you need it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Carnival
{
class Program
{
static void Main(string[] args)
{
//local variables
string name;
double money;
int choice = 0;
string newPrize;
//Game objects.
GameBooth balloonDartToss = new GameBooth(2, "tiger plush", "sticker");
GameBooth ringToss = new GameBooth(2, "bear keychain", "pencil");
GameBooth breakAPlate = new GameBooth(1.5, "pig plush", "plastic dinosaur");
Console.ForegroundColor = ConsoleColor.Cyan;
//asking player name
Console.Write("Welcome to the Carnival. What is your name? ");
name = Console.ReadLine();
//asking how much spending money the player has
Console.Write("How much money do you have? ");
money = Convert.ToDouble(Console.ReadLine());
Console.ResetColor();
//Creating player object.
Player Gambler = new Player(name, money);
//main program loop
while (choice != 4)
{
//print menu. Check out the local method below
printMenu();
//retrieve user choice. See the local method below
choice = getChoice();
//main switch. User Choices:
// 1 - we play Baloon Darts Toss and show prize
// 2 - we play ring Toss and show prize
// 3 - we play Break a Plate and show prize
// 4 - Show users all his prizes
switch (choice)
{
case 1:
newPrize = Gambler.Play(balloonDartToss);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(newPrize);
break;
case 2:
newPrize = Gambler.Play(ringToss);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(newPrize);
break;
case 3:
newPrize = Gambler.Play(breakAPlate);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(newPrize);
break;
case 4:
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("{0}, here is your prize list: {1}", Gambler.Name, Gambler.PrizesWon);
Console.ResetColor();
break;
}//end switch
}//end while
//next line simply pauses the program until you hit Enter.
Console.ReadLine();
}//end main
//this method prints the main menu
public static void printMenu()
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine();
Console.WriteLine("Select the game you would like to play:");
Console.WriteLine("1. Balloon Dart Toss");
Console.WriteLine("2. Ring Toss");
Console.WriteLine("3. Break a Plate");
Console.WriteLine("4. Get Prizes and Leave Carnival");
Console.Write("Enter Your Choice: ");
Console.ResetColor();
}//end printMenu
//this methods accepts user input 1-4
public static int getChoice()
{
Console.ForegroundColor = ConsoleColor.Yellow;
int input = 0;
do
{
Console.ForegroundColor = ConsoleColor.Yellow;
input = Convert.ToInt32(Console.ReadLine());
if (input < 1 || input > 4)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Out of range. Input 1-4 only");
Console.Write("Enter your choice: ");
Console.ResetColor();
}
} while (input < 1 || input > 4);
Console.ResetColor();
return input;
}
}
}
here is my other class if you need that too but you probably don't
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Carnival
{
class GameBooth
{
//properties
public double Cost { get; set; }
public string FirstPrize { get; set; }
public string ConsolationPrize { get; set; }
public int w { get; set; }
public int l { get; set; }
//constructors
public GameBooth(double c, string fp, string cp)
{
Cost = c;
FirstPrize = fp;
ConsolationPrize = cp;
}
//methods
public string Start()
{
Random r = new Random();
w = 1;
l = 1;
for (int i = 1; i < 3; i++)
{
int randomChoice = r.Next(0, 400);
if ( randomChoice == 1)
{
w++;
}
}
if (w == 3)
{
return FirstPrize;
}
else
{
return ConsolationPrize;
}
}
}
}
Update the line to:
PrizesWon = string.IsNullOrEmpty(PrizesWon) ? newPrize : newPrize + "," + PrizesWon;
This uses the conditional operator to return a different result depending on whether or not PrizesWon already has something in it.
In your code you had put (,) before newPrize. For solving this, you have to just put it after PrizesWon variable and it will look like this :
**PrizesWon = newPrize + PrizesWon + ",";**
I hope your problem will be solved by this.

Calling a method that expects an array of objects

I'm learning C# and have written a console program to save an an array of high scores to a file. Although the program works, how I have got it to work is making me feel uneasy and feels more of a hack than a solution so I was looking for guidance on how I should have written it.
What I am currently doing within the Main method is:
Declaring an array of highscore objects
Initialising them
Assigning some values to the array.
I am happy with what I have done up until now, it's the following two steps that make me uneasy
I then declare another HighScore object
I use this object to pass the array of highscores to the SaveHighScores method.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace HighScore
{
class HighScore
{
public string Name { get; set; }
public int Score { get; set; }
public void SaveHighScores(HighScore[] highScores)
{
string allHighScoresText = "";
foreach (HighScore score in highScores)
{
allHighScoresText += $"{score.Name},{score.Score}" + Environment.NewLine;
}
File.WriteAllText("C:/Temp/highscores.csv", allHighScoresText);
}
static void Main(string[] args)
{
HighScore[] highScore = new HighScore[2];
for (int i = 0; i < highScore.Length; i++)
{
highScore[i] = new HighScore();
}
highScore[0].Name = "A";
highScore[0].Score = 100;
highScore[1].Name = "B";
highScore[1].Score = 200;
// are the following two lines correct or am I missing something?
HighScore hs = new HighScore();
hs.SaveHighScores(highScore);
}
}
}
Make SaveHighScores static and you won't need an instance of HighScore to call it. (You can call it directly as HighScore.SaveHighScores())
I prefer to split the representation of your data from the actions that you perform on this data. So I would go for two classes, one for the Data and one for the Save/Load and other business logic
public class HighScore
{
public string Name { get; set; }
public int Score { get; set; }
}
// This class handles the core work to persist your data on the storage medium
// The class is static so you don't need to declare instances and use directly the methods available.
public static class Repo_HighScore
{
// For simplicity, no error Handling but, for a robust implementation,
// error handling is required
public static bool SaveHighScores(HighScore[] highScores)
{
StringBuilder allHighScoresText = new StringBuilder();
foreach (HighScore score in highScores)
allHighScoresText.AppendLine($"{score.Name},{score.Score}");
File.WriteAllText("C:/Temp/highscores.csv", allHighScoresText.ToString());
}
public static HighScore[] LoadHighScores()
{
List<HighScore> hs = new List<HighScore>();
foreach(string line in File.ReadLines("C:/Temp/highscores.csv"))
{
string[] parts = line.Split(',');
HighScore temp = new HighScore()
{ Name = parts[0], Score = Convert.ToInt32(parts[1])};
hs.Add(temp);
}
return hs.ToArray();
}
}

C# Foreach Loop Issue

I was just making this program to experiment with lists and such, and I was curious as to why in the foreach loop the Object always shows up as the "Minecraft" Wish object. Is it because it was the last Wish object to be created? And how can I fix it, so all 3 Wish objects which have been declared show up?
Thanks!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Wish iPod = new Wish("iPod", "Various", 299.00);
Wish Phone = new Wish("New Phone", "Various", 00.00);
Wish Minecraft = new Wish("Minecraft Account", "www.minecraft.net", 30.00);
List<Wish> Wishlist = new List<Wish>();
Wishlist.Add(Phone);
Wishlist.Add(iPod);
Wishlist.Add(Minecraft);
Console.WriteLine("Toby's Wishlist");
Console.WriteLine("If cost is 00.00, the Wish's cost varies.");
Console.WriteLine(" ");
foreach (Wish wish in Wishlist)
{
Console.WriteLine("---Wish---");
Console.WriteLine("Name: {0}", wish.getName());
Console.WriteLine("Store: {0}", wish.getStore());
Console.WriteLine("Cost: ${0}", wish.getCost().ToString());
Console.WriteLine("----------");
Console.WriteLine(" ");
}
Console.ReadLine();
}
}
public class Wish
{
static string Name, Store;
static double ApproxCost;
public Wish(string name, string store, double approxCost)
{
Name = name;
Store = store;
ApproxCost = approxCost;
}
public string getName()
{
return Name;
}
public string getStore()
{
return Store;
}
public double getCost()
{
return ApproxCost;
}
}
}
Remove static from Wish members declaration
static means that the data will be shared across all the instances. So static members are also so called class variables. While not static members - are object variables.
It's because in class Wish you declared Name, Score, and ApproxCost as static.

How to use BinaryReader and correctly input data into file?

I am working on my homework assignment and I am completely stuck! What I am trying to do is to use already defined input and save it to the file by using saveDataTo() method and read the input by using readDataFrom() method.
I am stuck on the first part. I am not sure if I have to initialize the data in Program.cs file first?
I don't know and I am stuck. Here is code and hope for some tips how I can accomplish this.
-- EDIT --
I can add instructions for purpose of both saveDataTo() and readDataFrom() methods:
The saveDataTo( ) method takes a parameter of BinaryWriter. The method
writes the values of all 5 properties of an book object to a file
stream associated with the writer (the association is done in the
Main( ) method of Program class). There is no need to open and close
the file stream and binary writer inside this method.
The readDataFrom( ) method takes a parameter of BinaryReader. The
method reads the values of all five properties of the Book object from
a file stream associated with the reader (the association is done in
the Main( ) method of Program class). There is no need to open and
close the file stream and binary reader inside this method.
So that gives me a clue that I should use and assign the properties to be saved in the file there?
-- EDIT --
Updated the code there. I do have a problem with content that is being saved into the file. I am not being showed the price. Why is that?
ff.APublisherNameTitle FirstNameLastName
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Lab_7
{
class Program
{
private const string FILE_NAME = "lab07.dat";
static void Main(string[] args)
{
//char ask;
/*
do
{
Console.Write("Enter Book Title: ");
publication.Title = Console.ReadLine();
Console.Write("Enter Author's First Name: ");
book.AuthorFirstName = Console.ReadLine();
Console.Write("Enter Author's Last Name: ");
book.AuthorLastName = Console.ReadLine();
Console.Write("Enter Publisher's Name: ");
publication.PublisherName = Console.ReadLine();
Console.Write("Enter Book Price: $");
publication.Price = float.Parse(Console.ReadLine());
Console.Write("Would like to enter another book? [Y or N] ");
ask = char.Parse(Console.ReadLine().ToUpper());
}
while (ask == char.Parse("Y"));
*/
Book book = new Book();
book.Price = 10.9F;
book.Title = "Title";
book.PublisherName = "PublisherName";
book.AuthorFirstName = "FirstName";
book.AuthorLastName = "LastName";
FileStream fileStream = new FileStream(FILE_NAME, FileMode.OpenOrCreate);
BinaryWriter write = new BinaryWriter(fileStream);
book.saveDataTo(write);
write.Close();
fileStream = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
BinaryReader read = new BinaryReader(fileStream);
book.readDataFrom(read);
read.Close();
}
}
}
Publication.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Lab_7
{
class Publication
{
private float price;
private string publisherName, title;
public float Price
{
get
{
return price;
}
set
{
price = value;
}
}
public string PublisherName
{
get
{
return publisherName;
}
set
{
publisherName = value;
}
}
public string Title
{
get
{
return title;
}
set
{
title = value;
}
}
public void display()
{
Console.WriteLine("{0}\n{1}\n{2}", title, publisherName, price);
}
}
}
Book.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Lab_7
{
class Book : Publication
{
private string authorFirstName, authorLastName;
public string AuthorFirstName
{
get
{
return authorFirstName;
}
set
{
authorFirstName = value;
}
}
public string AuthorLastName
{
get
{
return authorLastName;
}
set
{
authorLastName = value;
}
}
public new void display()
{
}
public string getAuthorName()
{
return authorFirstName + " " + authorLastName;
}
public void readDataFrom(BinaryReader r)
{
Price = r.ReadInt32();
PublisherName = r.ReadString();
Title = r.ReadString();
authorFirstName = r.ReadString();
authorLastName = r.ReadString();
}
public void saveDataTo(BinaryWriter w)
{
w.Write(base.Price);
w.Write(base.PublisherName);
w.Write(base.Title);
w.Write(AuthorFirstName);
w.Write(AuthorLastName);
}
}
}
Regards.
HelpNeeder.
You're asking whether to define the values in Program.cs or Book.cs, right? Well, it is fine to define the values in Program.cs, you just need to make sure all the values are given before writing the data.
So, since the function takes a BinaryWriter parameter that is supposedly initialized beforehand, this should work:
public void saveDataTo(BinaryWriter w)
{
w.Write(getAuthorName());
//etc...
}
But, just remember that you do need to define all the info somewhere (anywhere) before calling save data.
You assign your parameters to 2 different objects, see:
Publication publication = new Publication();
Book book = new Book();
Both are individual instances residing in memory.
You either have to refer the publication to the book like:
Book book = new Book();
Publication publication = (Publication)book;
or just assign the values currently assigned to the publication directly to the book so:
publication.PublisherName = "PublisherName";
becomes
book.PublisherName = "PublisherName";
Apart from that, you're working in C#, not Java. By convention its normal to start your methods with a Capital (Pascal Case)
EDIT
Your now shown the price when reaidng since you write it as a floating field (or double, cant see the definition) and read it as an integer.
Change from r.ReadInt32(); to r.ReadDouble(); or r.ReadSingle()

Categories