How to write commands for File/Json - c#

Below is the code I made but I don't know where to start.
I will be grateful for the hint.
I have no idea what i should do next..
I want to make a program that will have a few commands.
Adding a new planet
Planet Removal
Show the List
Save to JSON
displays planet data
public class MyDate
{
public int masa { get; set; }
public int sredni { get; set; }
}
public class Lad
{
public string PlanetName { get; set; }
public MyDate Szczegoly { get; set; }
}
class Program
{
static void Main()
{
string choice = Console.ReadLine();
//string choiceup = choice.ToUpper();
switch (choice)
{
case "Add":
Add();
return;
case "Save":
break;
case "List":
LoadList();
break;
case "Exit":
return;
}
}
public static void Add()
{
Console.WriteLine("Podaj nazwe planety");
string name = Console.ReadLine();
Console.WriteLine("Podaj mase");
int masa = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Podaj srednice");
int sred = Convert.ToInt16(Console.ReadLine());
List<Lad> _data = new List<Lad>();
_data.Add(new Lad()
{
PlanetName = name,
Szczegoly = new MyDate
{
masa = masa,
sredni = sred
}
});
var json = System.Text.Json.JsonSerializer.Serialize(_data);
Console.WriteLine(json);
string json2 = JsonConvert.SerializeObject(_data, Formatting.Indented);
File.AppendAllText(#"tescikkk.json", json2);
}
static List<Lad> LoadList()
{
string text = File.ReadAllText(#"tescikkk.json");
if (string.IsNullOrEmpty(text))
return new List<Lad>() { };
return JsonConvert.DeserializeObject<Lad[]>(text).ToList();
}
}

Related

How to write a function to take something out of a generic?

I am doing an assignment where you make a distribution company and have to add/remove food and chemical items from the company ledger. I wrote the add sections through generics but I am having difficulties with the remove part. I do not know how to write the logic for the remove items part where the user enter an item to remove and then if it matches it will remove it.
{
class Product : Food, Cleaner
{
public string food { get; set; }
public string cleaner { get; set; }
public string foodRemover { get; set; }
public string cleanerRemover { get; set; }
public void GenericMethod<T>(T param)
{
Console.WriteLine();
}
public class Food<T>
{
public T food { get; set; }
public T doFood (T f)
{
return f;
}
}
public class Cleaner<T>
{
public T cleaner { get; set; }
public T doCleaner(T c)
{
return c;
}
}
public void addFood()
{
Console.WriteLine("Food:");
Food<string> food1 = new Food<string>();
Console.Write(food1.doFood("Pizza"));
Food<int> food1index = new Food<int>() { food = 1 };
Console.Write(food1index.doFood(1));
Console.WriteLine();
Food<string> food2 = new Food<string>();
Console.Write(food2.doFood("Pasta"));
Food<int> food2index = new Food<int>() { food = 2 };
Console.Write(food2index.doFood(2));
Console.WriteLine();
Food<string> food3 = new Food<string>();
Console.Write(food3.doFood("Sushi"));
Food<int> food3index = new Food<int>() { food = 3 };
Console.Write(food3index.doFood(3));
Console.WriteLine();
}
public void removeFood(Food removeFood)
{
Console.WriteLine("Enter food name you want to remove");
foodRemover = Console.ReadLine();
if (foodRemover == )
{
}
}
public void addCleaner()
{
Console.WriteLine("Cleaners:");
Cleaner<string> cleaner1 = new Cleaner<string>();
Console.Write(cleaner1.doCleaner("Baking soda"));
Cleaner<int> cleanerindex1 = new Cleaner<int>();
Console.Write(cleanerindex1.doCleaner(1));
Cleaner<string> cleaner2 = new Cleaner<string>();
Console.Write(cleaner2.doCleaner("Mouth wash"));
Cleaner<int> cleanerindex2 = new Cleaner<int>();
Console.Write(cleanerindex2.doCleaner(2));
Cleaner<string> cleaner3 = new Cleaner<string>();
Console.Write(cleaner3.doCleaner("Toothpaste"));
Cleaner<int> cleanerindex3 = new Cleaner<int>();
Console.Write(cleanerindex3.doCleaner(3));
Console.WriteLine();
}
public void removeCleaner(Cleaner removeCleaner)
{
Console.WriteLine("Enter food name you want to remove");
cleanerRemover = Console.ReadLine();
}
}
}

How to parse text file and connect to database in C#?

I'm trying to parse the text file but unable to parse the contents under "Columns:", "Records:", "Relationships:" headings.
My text file format:
Database
Type: SQL Server
Connection String:Server=localhost\SQLEXPRESS;Database=master;Trusted_Connection=True;
DBName:FirstDataBase
Tables
Table
Name:TableName1
Columns:
ID,numeric,4
Name,name,20
Designation,varchar,20
Relationships:
Records:
9001,XYZ,Director
8038,MNO,Associate
9876,LOP,HR
Table
Name:TableName2
Columns:
ID,numeric,4
Name,name,20
Designation,varchar,20
Relationships:
TableName1,TableName2,FK,ID
Records:
8038,MNO,Associate
My C# code:
static void Main(string[] args)
{
Console.WriteLine("Enter file name");
string filep = Console.ReadLine();
string filePath = $"C:\\Files\\{filep}.txt";
List<Columns> col = new List<Columns>();
List<TableName> tn = new List<TableName>();
string[] lines = File.ReadAllLines(filePath);
foreach (var line in lines)
{
if (line.StartsWith("\t" + "\t" + "Name:"))
{
TableName newTN = new TableName();
string s = line.Split(':')[1];
newTN.TName = s;
tn.Add(newTN);
Console.WriteLine(s);
}
if (line.StartsWith("\t" + "\t" + "Columns:"))
{
// Here I'm stuck
}
}
}
One of my model classes:
public class Columns
{
public string CName { get; set; }
public string CType { get; set; }
public string CSize { get; set; }
public string Ckey { get; set; }
}
I've tried various codes but still, I'm unable to parse it. Solutions are welcome and thanks in advance.
I'm stuck at how to make the program read the next lines of particular heading and store it in a list. If it is solved then I can easily make queries and connect to the database.
Try following :
sing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApp1
{
class Program
{
const string FILENAME = #"c:\temp\test.txt";
static void Main(string[] args)
{
Database database = new Database(FILENAME);
}
}
public enum STATE
{
GET_DATABASE,
GET_TABLES
}
public enum TABLE_FIELD
{
NONE,
NAME,
COLUMNS,
RELATIONSHIPS,
RECORDS
}
public class Database
{
public string type { get; set; }
public string connection { get; set; }
public string name { get; set; }
public List<Table> tables { get; set; }
public Database(string filename)
{
StreamReader reader = new StreamReader(filename);
string line = "";
STATE state = STATE.GET_DATABASE;
TABLE_FIELD tableField = TABLE_FIELD.NONE;
Table table = null;
string[] splitLine;
while((line = reader.ReadLine()) != null)
{
line = line.Trim();
if (line.Length > 0)
{
switch (state)
{
case STATE.GET_DATABASE:
if (line == "Tables")
{
state = STATE.GET_TABLES;
}
else
{
if (line.Contains(":"))
{
splitLine = line.Split(new char[] { ':' });
switch (splitLine[0])
{
case "Type":
type = splitLine[1].Trim();
break;
case "Connection String":
connection = splitLine[1].Trim();
break;
case "DBName":
name = splitLine[1].Trim();
break;
}
}
}
break;
case STATE.GET_TABLES:
if(line == "Table")
{
if (tables == null) tables = new List<Table>();
table = new Table();
tables.Add(table);
}
else
{
if (line.Contains(":"))
{
splitLine = line.Split(new char[] { ':' });
switch (splitLine[0])
{
case "Name":
table.name = splitLine[1].Trim();
tableField = TABLE_FIELD.NAME;
break;
case "Columns":
connection = splitLine[1].Trim();
tableField = TABLE_FIELD.COLUMNS;
break;
case "Relationships":
name = splitLine[1].Trim();
tableField = TABLE_FIELD.RELATIONSHIPS;
break;
case "Records":
name = splitLine[1].Trim();
tableField = TABLE_FIELD.RECORDS;
break;
}
}
else
{
switch (tableField)
{
case TABLE_FIELD.COLUMNS:
if (table.columns == null) table.columns = new List<Column>();
Column column = new Column();
table.columns.Add(column);
splitLine = line.Split(new char[] { ',' });
column.name = splitLine[0];
column.type = (COLUMN_TYPE)Enum.Parse(typeof(COLUMN_TYPE), splitLine[1]);
column.length = int.Parse(splitLine[2]);
break;
case TABLE_FIELD.RECORDS:
splitLine = line.Split(new char[] { ',' });
if (table.records == null) table.records = new List<List<object>>();
List<object> row = new List<object>();
table.records.Add(row);
for(int i = 0; i < splitLine.Length; i++)
{
switch(table.columns[i].type)
{
case COLUMN_TYPE.numeric:
row.Add(int.Parse(splitLine[i]));
break;
case COLUMN_TYPE.name:
row.Add(splitLine[i]);
break;
case COLUMN_TYPE.varchar:
row.Add(splitLine[i]);
break;
}
}
break;
default:
break;
}
}
}
break;
}
}
}
}
}
public class Table
{
public string name { get; set; }
public List<Column> columns { get; set; }
public List<Relationship> relationships { get; set; }
public List<List<object>> records { get; set; }
}
public enum COLUMN_TYPE
{
numeric,
name,
varchar
}
public class Column
{
public string name { get; set; }
public COLUMN_TYPE type { get; set; }
public int length { get; set; }
}
public class Relationship
{
}
}

calling methods and arrays objects Library Book console app C#

My professor wants us to create a reusable class and console app that lists book objects. I got the first part of the assignment where I am supposed to print the books I created, but now I am stuck on the part where I have to modify the data and print again using the same method and then check out two books and print again. I have tried to look at example online and although some of them have helped, none have been able to get me to pass this roadblock.
class LibraryBook
{
private string _bookTitle;
private string _authorName;
private string _publisher;
private int _copyrightYear;
private string _callNumber;
public LibraryBook(string booktitle, string authorname, string publisher, int ccyear, string callnumber)
{
BookTitle = booktitle;
AuthorName = authorname;
Publisher = publisher;
CopyrightYear = ccyear;
CallNumber = callnumber;
}
public string BookTitle
{
get
{
return _bookTitle;
}
set
{
_bookTitle = value;
}
}
public string AuthorName
{
get
{
return _authorName;
}
set
{
_authorName = value;
}
}
public string Publisher
{
get
{
return _publisher;
}
set
{
_publisher = value;
}
}
public int CopyrightYear
{
get
{
return _copyrightYear;
}
set
{
const int CYEAR = 2019;
if (value > 0)
_copyrightYear = value;
else
_copyrightYear = CYEAR;
}
}
public string CallNumber
{
get
{
return _callNumber;
}
set
{
_callNumber = value;
}
}
public bool Avail;
public void CheckOut()
{
Avail = true;
}
public void ReturnToShelf()
{
Avail = false;
}
public bool IsCheckedOut()
{
return Avail;
}
public override string ToString()
{
return $"Book Title: {BookTitle}{Environment.NewLine}" +
$"Author Name: {AuthorName}{Environment.NewLine}" +
$"Publisher: {Publisher}{Environment.NewLine}" +
$"Copyright Year: {CopyrightYear}{Environment.NewLine}" +
$"Call Number: {CallNumber}{Environment.NewLine}" +
$"Checked Out: {IsCheckedOut()}{Environment.NewLine}";
}
}
}
class Program
{
static void Main(string[] args)
{
LibraryBook[] favBooksArray = new LibraryBook[5];
favBooksArray[0] = new LibraryBook("Harry Potter and the Philospher's Stone", "J.K. Rowling", "Scholastic Corporation", 1997, "HA-12.36");
favBooksArray[1] = new LibraryBook("Harry Potter and the Chamber of Secret", "J.K. Rowling", "Scholastic Corporation", 2001, "HA-13.48");
favBooksArray[2] = new LibraryBook("Tangerine", "Edward Bloor", "Harcourt", 1997, "TB-58.13");
favBooksArray[3] = new LibraryBook("Roll of Thunder, Hear My Cry", "Mildred D. Taylor", "Dial Press", 1976, "RT-15.22");
favBooksArray[4] = new LibraryBook("The Giver", "Lois Lowry", "Fake Publisher", -1, "Fk200-1");
WriteLine($"------LIBRARY BOOKS------{Environment.NewLine}");
BooksToConsole(favBooksArray);
WriteLine($"------CHANGES MADE----- {Environment.NewLine}");
ChangesToBooks(favBooksArray);
BooksToConsole(favBooksArray);
WriteLine($"------RETURNING BOOKS TO SHELF------{Environment.NewLine}");
ReturnBooksToConsole(favBooksArray);
BooksToConsole(favBooksArray);
}
public static void BooksToConsole(LibraryBook[] favBooksArray)
{
foreach (LibraryBook books in favBooksArray)
{
WriteLine($"{books}{Environment.NewLine}");
}
}
public static void ChangesToBooks(LibraryBook[] favBooksArray)
{
favBooksArray[1].AuthorName = "*****The Rock*****";
favBooksArray[3].BookTitle = "****Totally Not A Fake Name*****";
favBooksArray[1].CheckOut();
favBooksArray[4].CheckOut();
}
public static void ReturnBooksToConsole(LibraryBook[] favBooksArray)
{
favBooksArray[1].ReturnToShelf();
favBooksArray[4].ReturnToShelf();
}
}
}

Trying to figure out how to access list in a different method

This is my Code inside my Class. I'm trying to figure out how to access Questions list in DisplayQuestion. I have a program.cs that display a menu for a quiz and I can't have anything static.
public string Question { get; set; }
public List<string> Choices { get; set; }
public char[] CorrectChoice = { 'A', 'B', 'C', 'D' };
public List<string> Questions { get; set; }
These are my methods inside my class. I will need to access this list multiple times inside this class.
public void NewQuestion()
{
Questions = new List<string>();
Choices = new List<string>();
Console.WriteLine("Enter the question: ");
Questions.Add(Console.ReadLine());
Console.WriteLine("Enter Choice 1 for the question:");
Choices.Add(Console.ReadLine());
Console.WriteLine("Enter Choice 2 for the question: ");
Choices.Add(Console.ReadLine());
Console.WriteLine("Enter Choice 3 for the question: ");
Choices.Add(Console.ReadLine());
Console.WriteLine("Enter Choice 4 for the question:");
Choices.Add(Console.ReadLine());
// Console.WriteLine("Enter the correct choice(A,B,C,D)");
foreach (string choice in Choices)
{
Console.WriteLine();
Console.WriteLine(choice);
}
}
public void DisplayQuestions()
{
foreach(string question in Questions)
{
Console.WriteLine();
Console.WriteLine(question);
}
}
try declaring and initializing it to null in the global section or create a class with proper getter setter methods for it.
Don't feel constrained to do everything in one class. Even a rough, verbose attempt at separating concerns into separate classes helps with readability, maintainability, and sanity. Then, you're just a thoughtful refactor away from good code.
You are using C#, an OBJECT-oriented language. So go with the grain and embrace using objects.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Quiz_StackOverflow
{
class Program
{
static void Main(string[] args)
{
var quizGenerator = new QuizGenerator();
var quiz = quizGenerator.GenerateQuiz();
var quizProctor = new QuizProctor();
var grade = quizProctor.ProctorQuiz(quiz);
Console.WriteLine(grade.ToString());
Console.WriteLine("Done. Press any key to exit.");
Console.ReadKey();
}
}
public class QuizGenerator
{
public Quiz GenerateQuiz()
{
var problems = GenerateProblems();
var quiz = new Quiz()
{
Problems = problems
};
return quiz;
}
private List<Problem> GenerateProblems()
{
List<Problem> problems = new List<Problem>();
int numChoices = InputValidator.GetPositiveNumber("Enter number of problems: ");
for (int i = 0; i < numChoices; i++)
{
Problem problem = GenerateProblem();
problems.Add(problem);
}
return problems;
}
private Problem GenerateProblem()
{
var question = GenerateQuestion();
var choices = GenerateChoices();
var answer = GenerateAnswer(choices);
var problem = new Problem()
{
Question = question,
Choices = choices,
Answer = answer
};
return problem;
}
private string GenerateQuestion()
{
Console.WriteLine("Enter the question: ");
string question = Console.ReadLine();
return question;
}
private List<string> GenerateChoices()
{
List<string> choices = new List<string>();
int numChoices = InputValidator.GetPositiveNumber("Enter number of choices for the question: ");
for (int i=1; i<=numChoices; i++)
{
string choice = GenerateChoice(i);
choices.Add(choice);
}
return choices;
}
private string GenerateChoice(int index)
{
Console.WriteLine($"Enter Choice {index} for the question: ");
string choice = Console.ReadLine();
return choice;
}
private Answer GenerateAnswer(List<string> choices)
{
Console.WriteLine("Enter the answer: ");
string userChoice = InputValidator.GetUserChoice(new Problem() { Choices=choices });
var answer = new Answer()
{
Value = userChoice
};
return answer;
}
}
public class QuizProctor
{
public Grade ProctorQuiz(Quiz quiz)
{
var answers = new List<Answer>();
foreach(Problem problem in quiz.Problems)
{
Answer answer = ProctorProblem(problem);
answers.Add(answer);
}
Grade grade = quiz.Grade(answers);
return grade;
}
private Answer ProctorProblem(Problem problem)
{
string userChoice = InputValidator.GetUserChoice(problem);
var answer = new Answer()
{
Value = userChoice
};
return answer;
}
}
public class Quiz
{
public List<Problem> Problems { get; set; }
public Grade Grade(List<Answer> answers)
{
List<Answer> answerKey = Problems.Select(x => x.Answer).ToList();
var rawResults = new List<Tuple<Answer, Answer>>();
for(int i=0; i<answers.Count; i++)
{
Answer correct = answerKey[i];
Answer provided = answers[i];
rawResults.Add(new Tuple<Answer, Answer>(correct, provided));
}
return new Grade(rawResults);
}
}
public class Grade
{
private List<Tuple<Answer, Answer>> RawResults { get; set; }
public decimal Percent
{
get { return decimal.Divide(RawResults.Count(x => x.Item1.Equals(x.Item2)), RawResults.Count); }
}
public Grade(List<Tuple<Answer, Answer>> rawResults)
{
RawResults = rawResults;
}
public override string ToString()
{
return string.Format("You scored a {0:P2}.", Percent);
}
}
public class Problem
{
public string Question { get; set; }
public List<string> Choices { get; set; }
public Answer Answer { get; set; }
public string Prompt()
{
Func<int, char> numberToLetter = (int n) =>
{
return (char)('A' - 1 + n);
};
string prompt = Question;
for (int i=0; i<Choices.Count; i++)
{
string choice = Choices[i];
prompt += $"\n{numberToLetter(i+1)}) {choice}";
}
return prompt;
}
}
public class Answer
{
public string Value { get; set; }
public override string ToString()
{
return Value + "";
}
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
return (obj as Answer).Value.Equals(Value);
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
}
public static class InputValidator
{
public static int GetPositiveNumber(string prompt)
{
int number = -1;
while (number < 0)
{
Console.Write(prompt);
string input = Console.ReadLine();
try
{
number = int.Parse(input);
}
catch (Exception)
{
Console.WriteLine("ERROR: Please input a positive number.");
}
}
return number;
}
public static string GetUserChoice(Problem problem)
{
Func<char, int> letterToNumber = (char c) =>
{
if (char.IsLower(c))
{
return (int)(c - 'a' + 1);
}
return (int)(c - 'A' + 1);
};
char userChoiceLetter = '_';
while (!char.IsLetter(userChoiceLetter))
{
Console.WriteLine(problem.Prompt());
Console.Write("Answer: ");
var input = Console.ReadLine();
try
{
userChoiceLetter = char.Parse(input);
}
catch (Exception)
{
Console.WriteLine("ERROR: Please input a letter corresponding to your choice.");
}
}
int answerIndex = letterToNumber(userChoiceLetter) - 1;
return problem.Choices[answerIndex];
}
}
}

How to Create a simple atm program in c# using inheritance

I'm trying to create an e-ATM console app using C# using inheritance, but every time I debug I see that the derived class values are null, whereas the base class fields or properties are filled with values. Why is the derived class not showing the list with their data even after it is inherited from the base class?
class CreateAccount
{
string firstName, lastName, dateOfBirth, phoneNO, fathersName, mothersName;
double initialBalance; int pinNo = 100, accountNo = 1234, age; DateTime yearOfBirth;
protected static List<CreateAccount> data = new List<CreateAccount>();
protected string FirstName
{
get { return this.firstName; }
set
{
if (string.IsNullOrEmpty(value)) throw new Exception();
else firstName = value;
}
}
protected string LastName
{
get { return this.lastName; }
set
{
if (string.IsNullOrEmpty(value)) throw new Exception();
else lastName = value;
}
}
protected string DateOfBirth
{
get { return this.dateOfBirth; }
set
{
if (string.IsNullOrEmpty(value)) throw new Exception();
else dateOfBirth = value;
}
}
protected string PhoneNo
{
get { return this.phoneNO; }
set
{
if ((string.IsNullOrEmpty(value)) || value.Length != 10)
throw new Exception();
else
phoneNO = value;
}
}
protected string FathersName
{
get { return this.fathersName; }
set
{
if (string.IsNullOrEmpty(value))
throw new Exception();
else
fathersName = value;
}
}
protected string MothersName
{
get { return this.mothersName; }
set
{
if (string.IsNullOrEmpty(value))
throw new Exception();
else
mothersName = value;
}
}
protected double InititailBalance
{
get { return this.initialBalance; }
set
{
if (double.IsNaN(value))
throw new Exception();
else
initialBalance = value;
}
}
protected int PinNo
{
get { return this.pinNo; }
}
protected int AccountNo
{
get { return this.accountNo; }
}
public void GenerateAccount()
{
// code for asking user for their details.
data.Add(this);
}
}
class ATM :CreateAccount
{
public void Deposit()
{
Console.WriteLine("Enter your account number");
int accountNo = int.Parse(Console.ReadLine());
if (accountNo == AccountNo)
{
Console.WriteLine("Enter your amount you wish to deposit");
int amount = int.Parse(Console.ReadLine());
InititailBalance+= amount;
}
}
}
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Menu");
Console.WriteLine("1.Create Account");
Console.WriteLine("2.ATM");
Console.Write("Please enter your selections: ");
int select = int.Parse(Console.ReadLine());
switch (select)
{
case 1:
CreateAccount account = new CreateAccount();
account.GenerateAccount();
break;
case 2:
ATM atm = new ATM();
atm.Deposit();
break;
}
}
}
}
You are creating two different objects: a 'CreateAccount' Object and an 'ATM' object.
An ATM object does not automatically inherit the values from a previously created CreateAccount object, they are two completely different, unrelated entities.
So for your ATM object to have the same values that your CreateAccount object has, you would have to copy the CreateAccount object to your ATM object.
CreateAccount account = new CreateAccount();
//set account variables here
ATM atm = (ATM)account;
Here is how it's done with proper use of inheritance which is useless in this case actually. Dictionary is the proper datastructure to use in this case because you can avoid duplicates with it. Also from this code you might want to remove the accountNo from Account class to avoid duplicate numbers being kept and the ask it beffore calling GenerateAccount() method. So this is full console app:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ATM
{
class Account
{
string firstName, lastName, dateOfBirth, phoneNO, fathersName, mothersName;
double initialBalance;
int pinNo, accountNo, age;
DateTime yearOfBirth;
public Account()
{
pinNo = 100;
accountNo = 1234;
}
public string FirstName
{
get { return this.firstName; }
set
{
if (string.IsNullOrEmpty(value)) throw new Exception();
else firstName = value;
}
}
public string LastName
{
get { return this.lastName; }
set
{
if (string.IsNullOrEmpty(value)) throw new Exception();
else lastName = value;
}
}
public string DateOfBirth
{
get { return this.dateOfBirth; }
set
{
if (string.IsNullOrEmpty(value)) throw new Exception();
else dateOfBirth = value;
}
}
public string PhoneNo
{
get { return this.phoneNO; }
set
{
if ((string.IsNullOrEmpty(value)) || value.Length != 10)
throw new Exception();
else
phoneNO = value;
}
}
public string FathersName
{
get { return this.fathersName; }
set
{
if (string.IsNullOrEmpty(value))
throw new Exception();
else
fathersName = value;
}
}
public string MothersName
{
get { return this.mothersName; }
set
{
if (string.IsNullOrEmpty(value))
throw new Exception();
else
mothersName = value;
}
}
public double InititailBalance
{
get { return this.initialBalance; }
set
{
if (double.IsNaN(value))
throw new Exception();
else
initialBalance = value;
}
}
public int PinNo
{
get { return this.pinNo; }
}
public int AccountNo
{
get { return this.accountNo; }
}
public void GenerateAccount()
{
// code for asking user for their details.
}
}
class ATM
{
public static Dictionary<int, Account> AccountsList;
static ATM()
{
AccountsList = new Dictionary<int, Account>();
}
public void CreateAccount()
{
Account acc = new Account();
acc.GenerateAccount();
AccountsList.Add(acc.AccountNo, acc);
}
public void Deposit()
{
Console.WriteLine("Enter your account number");
int accountNo = int.Parse(Console.ReadLine());
if (AccountsList.ContainsKey(accountNo))
{
Console.WriteLine("Enter your amount you wish to deposit");
int amount = int.Parse(Console.ReadLine());
AccountsList[accountNo].InititailBalance += amount;
}
}
}
class Program
{
static void Main(string[] args)
{
ATM atm = new ATM();
while (true)
{
Console.WriteLine("Menu");
Console.WriteLine("1.Create Account");
Console.WriteLine("2.ATM");
Console.Write("Please enter your selections: ");
int select = int.Parse(Console.ReadLine());
switch (select)
{
case 1:
atm.CreateAccount();
break;
case 2:
atm.Deposit();
break;
default:
Console.WriteLine("Invalid selection!");
break;
}
}
}
}
}
CreateAccount is an operation of Atm and this is why I don't think you should be using inheritance. I propose this solution:
Class Account:
class Account
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public string PhoneNumber { get; set; }
public double Balance { get; set; }
// More properties here
...
}
Class Atm:
class Atm
{
public List<Account> Accounts { get; set; }
public Atm()
{
Accounts = new List<Account>();
}
public void CreateAccount()
{
var account = new Account();
// Get details from user here:
...
account.Balance = 0.0;
account.Id = Accounts.Count + 1;
Accounts.Add(account);
}
public void Deposit()
{
int accountId;
// Get input from the user here:
// --------------------------------
// 1. Check that the account exists
// 2. Deposit into the account.
...
}
Full example:
class Program
{
static void Main()
{
var atm = new Atm();
while (true)
{
int option;
Console.WriteLine();
Console.WriteLine("Menu:");
Console.WriteLine("1. Create Account");
Console.WriteLine("2. Deposit");
Console.WriteLine();
Console.Write("Please make a selection: ");
var input = int.TryParse(Console.ReadLine(), out option);
Console.WriteLine("-----------------");
switch (option)
{
case 1:
atm.CreateAccount();
break;
case 2:
atm.Deposit();
break;
}
}
}
}
class Account
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public string PhoneNumber { get; set; }
public double Balance { get; set; }
}
class Atm
{
public List<Account> Accounts { get; set; }
public Atm()
{
Accounts = new List<Account>();
}
public void CreateAccount()
{
var account = new Account();
Console.WriteLine("Create a new account!");
Console.WriteLine();
Console.Write("Enter first name: ");
account.FirstName = Console.ReadLine();
Console.Write("Enter last name: ");
account.LastName = Console.ReadLine();
Console.Write("Enter date of birth: ");
account.DateOfBirth = DateTime.Parse(Console.ReadLine());
Console.Write("Enter phone number: ");
account.PhoneNumber = Console.ReadLine();
account.Balance = 0.0;
account.Id = Accounts.Count + 1;
Accounts.Add(account);
}
public void Deposit()
{
int accountId;
Console.Write("Enter your account number: ");
int.TryParse(Console.ReadLine(), out accountId);
var account = Accounts.FirstOrDefault(a => a.Id == accountId);
if (account != null)
{
double amount;
Console.Write("Enter amount to deposit: ");
double.TryParse(Console.ReadLine(), out amount);
account.Balance += amount;
Console.Write("Your new balance is {0}", account.Balance);
}
else
{
Console.WriteLine("That account does not exist!");
}
}
}

Categories