SlideShare a Scribd company logo
1 of 18
Download to read offline
C#
i need help creating the instance of stream reader to read from a file the using statement will also
close the StreamReader
the txt files are "NumofAutos.txt" which is 5
and the txt files for "AutoData.txt"
which is Corolla
2013
23000
6
FORD
F150
2012
31000
8
BMW
328XI
2009
42000
3
CHEVY
Volt
2013
39000
5
NISSAN
Cube
2012
17500
5
this is the code that i have
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AutoInventory
{
//Class that holds the entire information related to Auto
class Auto
{
//Attributes
private string maker;
private string model;
private int year;
private double price;
private int inStock;
private double inventoryCost;
public static double totalInventoryCost = 0;
//Constructor
public Auto(string maker, string model, int year, double price, int inStock)
{
this.maker = maker;
this.model = model;
this.year = year;
this.price = price;
this.inStock = inStock;
}
//Setter methods
public void setMaker(string maker)
{
this.maker = maker;
}
public void setModel(string model)
{
this.model = model;
}
public void setYear(int year)
{
this.year = year;
}
public void setPrice(double price)
{
this.price = price;
}
public void setInStock(int stock)
{
this.inStock = stock;
}
//Getter Methods
public string getMaker()
{
return maker;
}
public string getModel()
{
return model;
}
public int getYear()
{
return year;
}
public double getPrice()
{
return price;
}
public int getInStock()
{
return inStock;
}
//Readonly Property
public double getInventoryCost()
{
return inventoryCost;
}
//Method that updates inventory
public void calcInventoryCost()
{
inventoryCost = price * inStock;
totalInventoryCost += inventoryCost;
}
}
//Main class
class Program
{
static void Main(string[] args)
{
//Getting number of autos
int count = getCount();
//Creating an array with size obtained
Auto[] autos = new Auto[count];
//Loading data
loadData(autos);
//Displaying and reading menu options
int option = menuOptions();
//Loop till user quits
while (true)
{
//Calling appropriate function
switch (option)
{
case 1: displayData(autos); break;
case 2: addAuto(autos); break;
case 3: sellAuto(autos); break;
case 4: saveExit(autos); Environment.Exit(0); break;
default: Console.WriteLine("  Invalid Option....   "); break;
}
option = menuOptions();
}
}
//Function that fetches the number of autos from file
public static int getCount()
{
int count = 0;
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("c:/NumofAuto.txt"))
{
string line;
//Reading count value
while ((line = sr.ReadLine()) != null)
{
count = Convert.ToInt32(line);
}
}
}
catch (Exception e)
{
//Handling exceptions
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
return count;
}
//Method that loads data from file to array
public static void loadData(Auto[] autos)
{
int i, length = autos.Length;
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("c:/AutoData.txt"))
{
string maker, model;
int year, inStock;
double price;
//Reading data from file and storing in array
for (i = 0; i < length; i++)
{
maker = sr.ReadLine();
model = sr.ReadLine();
year = Convert.ToInt32(sr.ReadLine());
price = Convert.ToDouble(sr.ReadLine());
inStock = Convert.ToInt32(sr.ReadLine());
Auto temp = new Auto(maker, model, year, price, inStock);
temp.calcInventoryCost();
autos[i] = temp;
}
}
}
catch (Exception e)
{
//Handling exceptions
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
//Method that prints menu options
public static int menuOptions()
{
int option;
//Diplay menu
Console.WriteLine(" **** MENU ****  ");
Console.Write(" 1 - Display 2 - Add Auto 3 - SellAuto 4 - SaveExit   Your option:
");
option = Convert.ToInt32(Console.ReadLine());
//Read option
return option;
}
//Method that displays data available in array
public static void displayData(Auto[] autos)
{
//Looping and printing each auto data
for (int i = 0; i < autos.Length; i++)
{
Console.WriteLine(" ");
Console.WriteLine(autos[i].getMaker() + " " + autos[i].getModel() + " " +
autos[i].getYear() + " " + autos[i].getPrice() + " " + autos[i].getInStock());
}
Console.WriteLine(" ");
}
//Method that adds auto to file
public static void addAuto(Auto[] autos)
{
int pos = -1;
string maker, model;
int year, inStock;
double price;
//Reading data
Console.Write(" Input Maker: ");
maker = Console.ReadLine();
Console.Write(" Input Model: ");
model = Console.ReadLine();
Console.Write(" Input Year: ");
year = Convert.ToInt32(Console.ReadLine());
Console.Write(" Input Price: ");
price = Convert.ToDouble(Console.ReadLine());
Console.Write(" Input InStock: ");
inStock = Convert.ToInt32(Console.ReadLine());
//Getting the position of auto
for (int i = 0; i < autos.Length; i++)
{
if (maker.Equals(autos[i].getMaker()))
{
pos = i;
}
}
//If auto doesn;t exist
if (pos == -1)
{
//Resize and add new auto
Array.Resize(ref autos, (autos.Length + 1));
Auto temp = new Auto(maker, model, year, price, inStock);
autos[autos.Length - 1] = temp;
Console.WriteLine(" Auto add Success....  ");
}
else
{
//If already exists just increment stock
autos[pos].setInStock(autos[pos].getInStock() + inStock);
Console.WriteLine(" Auto already exist!! Stock updated....  ");
}
Console.WriteLine(" ");
}
//Method that sells auto
public static void sellAuto(Auto[] autos)
{
int pos = -1;
string maker;
//Reading information from user
Console.Write(" Input Maker: ");
maker = Console.ReadLine();
//Looping and getting data
for (int i = 0; i < autos.Length; i++)
{
if (maker.Equals(autos[i].getMaker()))
{
pos = i;
}
}
//If auto doesn'e exist
if (pos == -1)
{
Console.WriteLine(" Error!!!! No Auto exists with the given name....  ");
}
else
{
//If exits but doesn't have enough stock
if ((autos[pos].getInStock()) - 1 < 0)
{
Console.WriteLine(" Error!!!! Stock not available....  ");
}
else
{
//Updating the stock
autos[pos].setInStock(autos[pos].getInStock() - 1);
Console.WriteLine(" Auto Sale Success....  ");
}
}
}
//Method that writes data from array to file
public static void saveExit(Auto[] autos)
{
//Writting data to file
using (StreamWriter file = new StreamWriter("C:/AutoData.txt"))
{
//Fetching data from array and writting to file
foreach (Auto auto in autos)
{
file.WriteLine(auto.getMaker());
file.WriteLine(auto.getModel());
file.WriteLine(auto.getYear());
file.WriteLine(auto.getPrice());
file.WriteLine(auto.getInStock() + 1);
}
}
Console.WriteLine(" Save Success....  ");
}
}
}
Solution
using System;
using System.IO;
namespace AutoInventory
{
//Class that holds the entire information related to Auto
class Auto
{
//Attributes
private string maker;
private string model;
private int year;
private double price;
private int inStock;
private double inventoryCost;
public static double totalInventoryCost = 0;
//Constructor
public Auto(string maker, string model, int year, double price, int inStock)
{
this.maker = maker;
this.model = model;
this.year = year;
this.price = price;
this.inStock = inStock;
}
//Setter methods
public void setMaker(string maker)
{
this.maker = maker;
}
public void setModel(string model)
{
this.model = model;
}
public void setYear(int year)
{
this.year = year;
}
public void setPrice(double price)
{
this.price = price;
}
public void setInStock(int stock)
{
this.inStock = stock;
}
//Getter Methods
public string getMaker()
{
return maker;
}
public string getModel()
{
return model;
}
public int getYear()
{
return year;
}
public double getPrice()
{
return price;
}
public int getInStock()
{
return inStock;
}
//Readonly Property
public double getInventoryCost()
{
return inventoryCost;
}
//Method that updates inventory
public void calcInventoryCost()
{
inventoryCost = price * inStock;
totalInventoryCost += inventoryCost;
}
}
//Main class
class Program
{
static void Main(string[] args)
{
//Getting number of autos
int count = getCount();
//Creating an array with size obtained
Auto[] autos = new Auto[count];
//Loading data
loadData(autos);
//Displaying and reading menu options
int option = menuOptions();
//Loop till user quits
while (true)
{
//Calling appropriate function
switch (option)
{
case 1: displayData(autos); break;
case 2: addAuto(autos); break;
case 3: sellAuto(autos); break;
case 4: saveExit(autos); Environment.Exit(0); break;
default: Console.WriteLine("  Invalid Option....   "); break;
}
option = menuOptions();
}
}
//Function that fetches the number of autos from file
public static int getCount()
{
int count=0;
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("f://NumofAutos.txt"))
{
//Reading count value
int.TryParse(sr.ReadLine().ToString(), out count);
}
}
catch (Exception e)
{
//Handling exceptions
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
return count;
}
//Method that loads data from file to array
public static void loadData(Auto[] autos)
{
int i, length = autos.Length;
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("f://AutoData.txt"))
{
string maker, model;
int year, inStock;
double price;
//Reading data from file and storing in array
for (i = 0; i < length; i++)
{
maker = sr.ReadLine().ToString();
model = sr.ReadLine().ToString();
int.TryParse(sr.ReadLine().ToString(), out year);
// year = Convert.ToInt32(sr.ReadLine());
double.TryParse(sr.ReadLine().ToString(), out price);
//price = Convert.ToDouble(sr.ReadLine());
int.TryParse(sr.ReadLine().ToString(), out inStock);
//inStock = Convert.ToInt32(sr.ReadLine());
//Auto temp = new Auto(maker, model, year, price, inStock);
//temp.calcInventoryCost();
// Console.WriteLine(maker+", "+ model+", "+ year+", "+ price+", "+ inStock+" ");
autos[i] = new Auto(maker, model, year, price, inStock);
autos[i].calcInventoryCost();
}
}
}
catch (Exception e)
{
//Handling exceptions
Console.WriteLine("The file AutoData.txt could not be read:");
Console.WriteLine(e.Message);
}
}
//Method that prints menu options
public static int menuOptions()
{
int option;
//Diplay menu
Console.WriteLine(" **** MENU ****  ");
Console.Write(" 1 - Display 2 - Add Auto 3 - SellAuto 4 - SaveExit   Your option: ");
option = Convert.ToInt32(Console.ReadLine());
//Read option
return option;
}
//Method that displays data available in array
public static void displayData(Auto[] autos)
{
//Looping and printing each auto data
for (int i = 0; i < autos.Length; i++)
{
Console.WriteLine(" ");
Console.WriteLine(autos[i].getMaker() + " " + autos[i].getModel() + " " + autos[i].getYear()
+ " " + autos[i].getPrice() + " " + autos[i].getInStock());
}
Console.WriteLine(" ");
}
//Method that adds auto to file
public static void addAuto(Auto[] autos)
{
int pos = -1;
string maker, model;
int year, inStock;
double price;
//Reading data
Console.Write(" Input Maker: ");
maker = Console.ReadLine();
Console.Write(" Input Model: ");
model = Console.ReadLine();
Console.Write(" Input Year: ");
year = Convert.ToInt32(Console.ReadLine());
Console.Write(" Input Price: ");
price = Convert.ToDouble(Console.ReadLine());
Console.Write(" Input InStock: ");
inStock = Convert.ToInt32(Console.ReadLine());
//Getting the position of auto
for (int i = 0; i < autos.Length; i++)
{
if (maker.Equals(autos[i].getMaker()))
{
pos = i;
}
}
//If auto doesn;t exist
if (pos == -1)
{
//Resize and add new auto
Array.Resize(ref autos, (autos.Length + 1));
Auto temp = new Auto(maker, model, year, price, inStock);
autos[autos.Length - 1] = temp;
Console.WriteLine(" Auto add Success....  ");
}
else
{
//If already exists just increment stock
autos[pos].setInStock(autos[pos].getInStock() + inStock);
Console.WriteLine(" Auto already exist!! Stock updated....  ");
}
Console.WriteLine(" ");
}
//Method that sells auto
public static void sellAuto(Auto[] autos)
{
int pos = -1;
string maker;
//Reading information from user
Console.Write(" Input Maker: ");
maker = Console.ReadLine();
//Looping and getting data
for (int i = 0; i < autos.Length; i++)
{
if (maker.Equals(autos[i].getMaker()))
{
pos = i;
}
}
//If auto doesn'e exist
if (pos == -1)
{
Console.WriteLine(" Error!!!! No Auto exists with the given name....  ");
}
else
{
//If exits but doesn't have enough stock
if ((autos[pos].getInStock()) - 1 < 0)
{
Console.WriteLine(" Error!!!! Stock not available....  ");
}
else
{
//Updating the stock
autos[pos].setInStock(autos[pos].getInStock() - 1);
Console.WriteLine(" Auto Sale Success....  ");
}
}
}
//Method that writes data from array to file
public static void saveExit(Auto[] autos)
{
//Writting data to file
using (StreamWriter file = new StreamWriter("f://AutoData.txt"))
{
//Fetching data from array and writting to file
foreach (Auto auto in autos)
{
file.WriteLine(auto.getMaker());
file.WriteLine(auto.getModel());
file.WriteLine(auto.getYear());
file.WriteLine(auto.getPrice());
file.WriteLine(auto.getInStock() + 1);
}
}
Console.WriteLine(" Save Success....  ");
}
}
}
changes are made only to the getCount() and loadData() functions

More Related Content

Similar to C#i need help creating the instance of stream reader to read from .pdf

Create a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdfCreate a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdfmalavshah9013
 
C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfyamew16788
 
#include iostream #include string #include fstream std.docx
#include iostream #include string #include fstream  std.docx#include iostream #include string #include fstream  std.docx
#include iostream #include string #include fstream std.docxajoy21
 
import java.util.Scanner;import java.text.DecimalFormat;import j.pdf
import java.util.Scanner;import java.text.DecimalFormat;import j.pdfimport java.util.Scanner;import java.text.DecimalFormat;import j.pdf
import java.util.Scanner;import java.text.DecimalFormat;import j.pdfKUNALHARCHANDANI1
 
In this assignment you will practice creating classes and enumeratio.pdf
In this assignment you will practice creating classes and enumeratio.pdfIn this assignment you will practice creating classes and enumeratio.pdf
In this assignment you will practice creating classes and enumeratio.pdfivylinvaydak64229
 
The Ring programming language version 1.10 book - Part 97 of 212
The Ring programming language version 1.10 book - Part 97 of 212The Ring programming language version 1.10 book - Part 97 of 212
The Ring programming language version 1.10 book - Part 97 of 212Mahmoud Samir Fayed
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design PatternsStefano Fago
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handlingsanya6900
 
The Ring programming language version 1.7 book - Part 87 of 196
The Ring programming language version 1.7 book - Part 87 of 196The Ring programming language version 1.7 book - Part 87 of 196
The Ring programming language version 1.7 book - Part 87 of 196Mahmoud Samir Fayed
 
Loops in C# for loops while and do while loop.
Loops in C# for loops while and do while loop.Loops in C# for loops while and do while loop.
Loops in C# for loops while and do while loop.Abid Kohistani
 
First Failure Data Capture for your enterprise application with WebSphere App...
First Failure Data Capture for your enterprise application with WebSphere App...First Failure Data Capture for your enterprise application with WebSphere App...
First Failure Data Capture for your enterprise application with WebSphere App...Rohit Kelapure
 
(9) cpp abstractions separated_compilation_and_binding_part_ii
(9) cpp abstractions separated_compilation_and_binding_part_ii(9) cpp abstractions separated_compilation_and_binding_part_ii
(9) cpp abstractions separated_compilation_and_binding_part_iiNico Ludwig
 
Gift-VT Tools Development Overview
Gift-VT Tools Development OverviewGift-VT Tools Development Overview
Gift-VT Tools Development Overviewstn_tkiller
 
Production.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdfProduction.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdfsooryasalini
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2Warui Maina
 

Similar to C#i need help creating the instance of stream reader to read from .pdf (20)

Create a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdfCreate a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdf
 
C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdf
 
Lecture5
Lecture5Lecture5
Lecture5
 
39927902 c-labmanual
39927902 c-labmanual39927902 c-labmanual
39927902 c-labmanual
 
39927902 c-labmanual
39927902 c-labmanual39927902 c-labmanual
39927902 c-labmanual
 
#include iostream #include string #include fstream std.docx
#include iostream #include string #include fstream  std.docx#include iostream #include string #include fstream  std.docx
#include iostream #include string #include fstream std.docx
 
import java.util.Scanner;import java.text.DecimalFormat;import j.pdf
import java.util.Scanner;import java.text.DecimalFormat;import j.pdfimport java.util.Scanner;import java.text.DecimalFormat;import j.pdf
import java.util.Scanner;import java.text.DecimalFormat;import j.pdf
 
In this assignment you will practice creating classes and enumeratio.pdf
In this assignment you will practice creating classes and enumeratio.pdfIn this assignment you will practice creating classes and enumeratio.pdf
In this assignment you will practice creating classes and enumeratio.pdf
 
The Ring programming language version 1.10 book - Part 97 of 212
The Ring programming language version 1.10 book - Part 97 of 212The Ring programming language version 1.10 book - Part 97 of 212
The Ring programming language version 1.10 book - Part 97 of 212
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
 
The Ring programming language version 1.7 book - Part 87 of 196
The Ring programming language version 1.7 book - Part 87 of 196The Ring programming language version 1.7 book - Part 87 of 196
The Ring programming language version 1.7 book - Part 87 of 196
 
Loops in C# for loops while and do while loop.
Loops in C# for loops while and do while loop.Loops in C# for loops while and do while loop.
Loops in C# for loops while and do while loop.
 
Day 1
Day 1Day 1
Day 1
 
First Failure Data Capture for your enterprise application with WebSphere App...
First Failure Data Capture for your enterprise application with WebSphere App...First Failure Data Capture for your enterprise application with WebSphere App...
First Failure Data Capture for your enterprise application with WebSphere App...
 
(9) cpp abstractions separated_compilation_and_binding_part_ii
(9) cpp abstractions separated_compilation_and_binding_part_ii(9) cpp abstractions separated_compilation_and_binding_part_ii
(9) cpp abstractions separated_compilation_and_binding_part_ii
 
Gift-VT Tools Development Overview
Gift-VT Tools Development OverviewGift-VT Tools Development Overview
Gift-VT Tools Development Overview
 
Production.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdfProduction.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdf
 
Java 14
Java 14 Java 14
Java 14
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
 

More from ajantha11

C) Find two numbers with a prescribed difference such that a predefi.pdf
C) Find two numbers with a prescribed difference such that a predefi.pdfC) Find two numbers with a prescribed difference such that a predefi.pdf
C) Find two numbers with a prescribed difference such that a predefi.pdfajantha11
 
By not connecting all the LPC1768 microcontroller pins to the mbed e.pdf
By not connecting all the LPC1768 microcontroller pins to the mbed e.pdfBy not connecting all the LPC1768 microcontroller pins to the mbed e.pdf
By not connecting all the LPC1768 microcontroller pins to the mbed e.pdfajantha11
 
Butterflies Red Blue Orange Yellow Collected in spring 14 27 9 4.pdf
Butterflies Red Blue Orange Yellow Collected in spring 14 27 9 4.pdfButterflies Red Blue Orange Yellow Collected in spring 14 27 9 4.pdf
Butterflies Red Blue Orange Yellow Collected in spring 14 27 9 4.pdfajantha11
 
Calculate the expected return on stock of United, Inc.Round the a.pdf
Calculate the expected return on stock of United, Inc.Round the a.pdfCalculate the expected return on stock of United, Inc.Round the a.pdf
Calculate the expected return on stock of United, Inc.Round the a.pdfajantha11
 
Calculate the expected return on stockState of the economyProbab.pdf
Calculate the expected return on stockState of the economyProbab.pdfCalculate the expected return on stockState of the economyProbab.pdf
Calculate the expected return on stockState of the economyProbab.pdfajantha11
 
Calculate the expected return on stockState of economy            .pdf
Calculate the expected return on stockState of economy            .pdfCalculate the expected return on stockState of economy            .pdf
Calculate the expected return on stockState of economy            .pdfajantha11
 
Calculate the complex number (1-i)^11SolutionTo write the alg.pdf
Calculate the complex number (1-i)^11SolutionTo write the alg.pdfCalculate the complex number (1-i)^11SolutionTo write the alg.pdf
Calculate the complex number (1-i)^11SolutionTo write the alg.pdfajantha11
 
Business Manager and Director of FinanceDetermine the one duty.pdf
Business Manager and Director of FinanceDetermine the one duty.pdfBusiness Manager and Director of FinanceDetermine the one duty.pdf
Business Manager and Director of FinanceDetermine the one duty.pdfajantha11
 
Business LawSome businesses are aggressive at suing the media that.pdf
Business LawSome businesses are aggressive at suing the media that.pdfBusiness LawSome businesses are aggressive at suing the media that.pdf
Business LawSome businesses are aggressive at suing the media that.pdfajantha11
 
Business LawIn the following situations, two parties claim the s.pdf
Business LawIn the following situations, two parties claim the s.pdfBusiness LawIn the following situations, two parties claim the s.pdf
Business LawIn the following situations, two parties claim the s.pdfajantha11
 
Business Law Class MSACH.05 Criminal Law (2) set 10William Parks.pdf
Business Law Class MSACH.05 Criminal Law (2) set 10William Parks.pdfBusiness Law Class MSACH.05 Criminal Law (2) set 10William Parks.pdf
Business Law Class MSACH.05 Criminal Law (2) set 10William Parks.pdfajantha11
 
Calculate 1+i+i^2+i^3+i^4+......+i^10.SolutionWe know that i^2.pdf
Calculate 1+i+i^2+i^3+i^4+......+i^10.SolutionWe know that i^2.pdfCalculate 1+i+i^2+i^3+i^4+......+i^10.SolutionWe know that i^2.pdf
Calculate 1+i+i^2+i^3+i^4+......+i^10.SolutionWe know that i^2.pdfajantha11
 
Business intelligence (BI) _____________.A)is knowledge technology w.pdf
Business intelligence (BI) _____________.A)is knowledge technology w.pdfBusiness intelligence (BI) _____________.A)is knowledge technology w.pdf
Business intelligence (BI) _____________.A)is knowledge technology w.pdfajantha11
 
Calculate 25(4+3i) +25(4-3i)SolutionWell factorize by 25 .pdf
Calculate 25(4+3i) +25(4-3i)SolutionWell factorize by 25 .pdfCalculate 25(4+3i) +25(4-3i)SolutionWell factorize by 25 .pdf
Calculate 25(4+3i) +25(4-3i)SolutionWell factorize by 25 .pdfajantha11
 
Cablevision has just hired a new director of budgeting, LACEY DUBOIS.pdf
Cablevision has just hired a new director of budgeting, LACEY DUBOIS.pdfCablevision has just hired a new director of budgeting, LACEY DUBOIS.pdf
Cablevision has just hired a new director of budgeting, LACEY DUBOIS.pdfajantha11
 
c. Financial PerspectiveHow can we be good stewards of institution.pdf
c. Financial PerspectiveHow can we be good stewards of institution.pdfc. Financial PerspectiveHow can we be good stewards of institution.pdf
c. Financial PerspectiveHow can we be good stewards of institution.pdfajantha11
 
c.Explain why in Cross-Cultural Negotiations, the heuristic of avail.pdf
c.Explain why in Cross-Cultural Negotiations, the heuristic of avail.pdfc.Explain why in Cross-Cultural Negotiations, the heuristic of avail.pdf
c.Explain why in Cross-Cultural Negotiations, the heuristic of avail.pdfajantha11
 

More from ajantha11 (17)

C) Find two numbers with a prescribed difference such that a predefi.pdf
C) Find two numbers with a prescribed difference such that a predefi.pdfC) Find two numbers with a prescribed difference such that a predefi.pdf
C) Find two numbers with a prescribed difference such that a predefi.pdf
 
By not connecting all the LPC1768 microcontroller pins to the mbed e.pdf
By not connecting all the LPC1768 microcontroller pins to the mbed e.pdfBy not connecting all the LPC1768 microcontroller pins to the mbed e.pdf
By not connecting all the LPC1768 microcontroller pins to the mbed e.pdf
 
Butterflies Red Blue Orange Yellow Collected in spring 14 27 9 4.pdf
Butterflies Red Blue Orange Yellow Collected in spring 14 27 9 4.pdfButterflies Red Blue Orange Yellow Collected in spring 14 27 9 4.pdf
Butterflies Red Blue Orange Yellow Collected in spring 14 27 9 4.pdf
 
Calculate the expected return on stock of United, Inc.Round the a.pdf
Calculate the expected return on stock of United, Inc.Round the a.pdfCalculate the expected return on stock of United, Inc.Round the a.pdf
Calculate the expected return on stock of United, Inc.Round the a.pdf
 
Calculate the expected return on stockState of the economyProbab.pdf
Calculate the expected return on stockState of the economyProbab.pdfCalculate the expected return on stockState of the economyProbab.pdf
Calculate the expected return on stockState of the economyProbab.pdf
 
Calculate the expected return on stockState of economy            .pdf
Calculate the expected return on stockState of economy            .pdfCalculate the expected return on stockState of economy            .pdf
Calculate the expected return on stockState of economy            .pdf
 
Calculate the complex number (1-i)^11SolutionTo write the alg.pdf
Calculate the complex number (1-i)^11SolutionTo write the alg.pdfCalculate the complex number (1-i)^11SolutionTo write the alg.pdf
Calculate the complex number (1-i)^11SolutionTo write the alg.pdf
 
Business Manager and Director of FinanceDetermine the one duty.pdf
Business Manager and Director of FinanceDetermine the one duty.pdfBusiness Manager and Director of FinanceDetermine the one duty.pdf
Business Manager and Director of FinanceDetermine the one duty.pdf
 
Business LawSome businesses are aggressive at suing the media that.pdf
Business LawSome businesses are aggressive at suing the media that.pdfBusiness LawSome businesses are aggressive at suing the media that.pdf
Business LawSome businesses are aggressive at suing the media that.pdf
 
Business LawIn the following situations, two parties claim the s.pdf
Business LawIn the following situations, two parties claim the s.pdfBusiness LawIn the following situations, two parties claim the s.pdf
Business LawIn the following situations, two parties claim the s.pdf
 
Business Law Class MSACH.05 Criminal Law (2) set 10William Parks.pdf
Business Law Class MSACH.05 Criminal Law (2) set 10William Parks.pdfBusiness Law Class MSACH.05 Criminal Law (2) set 10William Parks.pdf
Business Law Class MSACH.05 Criminal Law (2) set 10William Parks.pdf
 
Calculate 1+i+i^2+i^3+i^4+......+i^10.SolutionWe know that i^2.pdf
Calculate 1+i+i^2+i^3+i^4+......+i^10.SolutionWe know that i^2.pdfCalculate 1+i+i^2+i^3+i^4+......+i^10.SolutionWe know that i^2.pdf
Calculate 1+i+i^2+i^3+i^4+......+i^10.SolutionWe know that i^2.pdf
 
Business intelligence (BI) _____________.A)is knowledge technology w.pdf
Business intelligence (BI) _____________.A)is knowledge technology w.pdfBusiness intelligence (BI) _____________.A)is knowledge technology w.pdf
Business intelligence (BI) _____________.A)is knowledge technology w.pdf
 
Calculate 25(4+3i) +25(4-3i)SolutionWell factorize by 25 .pdf
Calculate 25(4+3i) +25(4-3i)SolutionWell factorize by 25 .pdfCalculate 25(4+3i) +25(4-3i)SolutionWell factorize by 25 .pdf
Calculate 25(4+3i) +25(4-3i)SolutionWell factorize by 25 .pdf
 
Cablevision has just hired a new director of budgeting, LACEY DUBOIS.pdf
Cablevision has just hired a new director of budgeting, LACEY DUBOIS.pdfCablevision has just hired a new director of budgeting, LACEY DUBOIS.pdf
Cablevision has just hired a new director of budgeting, LACEY DUBOIS.pdf
 
c. Financial PerspectiveHow can we be good stewards of institution.pdf
c. Financial PerspectiveHow can we be good stewards of institution.pdfc. Financial PerspectiveHow can we be good stewards of institution.pdf
c. Financial PerspectiveHow can we be good stewards of institution.pdf
 
c.Explain why in Cross-Cultural Negotiations, the heuristic of avail.pdf
c.Explain why in Cross-Cultural Negotiations, the heuristic of avail.pdfc.Explain why in Cross-Cultural Negotiations, the heuristic of avail.pdf
c.Explain why in Cross-Cultural Negotiations, the heuristic of avail.pdf
 

Recently uploaded

Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 

Recently uploaded (20)

Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 

C#i need help creating the instance of stream reader to read from .pdf

  • 1. C# i need help creating the instance of stream reader to read from a file the using statement will also close the StreamReader the txt files are "NumofAutos.txt" which is 5 and the txt files for "AutoData.txt" which is Corolla 2013 23000 6 FORD F150 2012 31000 8 BMW 328XI 2009 42000 3 CHEVY Volt 2013 39000 5 NISSAN Cube 2012 17500 5 this is the code that i have using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text;
  • 2. namespace AutoInventory { //Class that holds the entire information related to Auto class Auto { //Attributes private string maker; private string model; private int year; private double price; private int inStock; private double inventoryCost; public static double totalInventoryCost = 0; //Constructor public Auto(string maker, string model, int year, double price, int inStock) { this.maker = maker; this.model = model; this.year = year; this.price = price; this.inStock = inStock; } //Setter methods public void setMaker(string maker) { this.maker = maker; } public void setModel(string model) { this.model = model; } public void setYear(int year) { this.year = year; } public void setPrice(double price)
  • 3. { this.price = price; } public void setInStock(int stock) { this.inStock = stock; } //Getter Methods public string getMaker() { return maker; } public string getModel() { return model; } public int getYear() { return year; } public double getPrice() { return price; } public int getInStock() { return inStock; } //Readonly Property public double getInventoryCost() { return inventoryCost; } //Method that updates inventory public void calcInventoryCost() {
  • 4. inventoryCost = price * inStock; totalInventoryCost += inventoryCost; } } //Main class class Program { static void Main(string[] args) { //Getting number of autos int count = getCount(); //Creating an array with size obtained Auto[] autos = new Auto[count]; //Loading data loadData(autos); //Displaying and reading menu options int option = menuOptions(); //Loop till user quits while (true) { //Calling appropriate function switch (option) { case 1: displayData(autos); break; case 2: addAuto(autos); break; case 3: sellAuto(autos); break; case 4: saveExit(autos); Environment.Exit(0); break; default: Console.WriteLine(" Invalid Option.... "); break; } option = menuOptions(); } } //Function that fetches the number of autos from file public static int getCount() {
  • 5. int count = 0; try { // Create an instance of StreamReader to read from a file. // The using statement also closes the StreamReader. using (StreamReader sr = new StreamReader("c:/NumofAuto.txt")) { string line; //Reading count value while ((line = sr.ReadLine()) != null) { count = Convert.ToInt32(line); } } } catch (Exception e) { //Handling exceptions Console.WriteLine("The file could not be read:"); Console.WriteLine(e.Message); } return count; } //Method that loads data from file to array public static void loadData(Auto[] autos) { int i, length = autos.Length; try { // Create an instance of StreamReader to read from a file. // The using statement also closes the StreamReader. using (StreamReader sr = new StreamReader("c:/AutoData.txt")) { string maker, model; int year, inStock; double price;
  • 6. //Reading data from file and storing in array for (i = 0; i < length; i++) { maker = sr.ReadLine(); model = sr.ReadLine(); year = Convert.ToInt32(sr.ReadLine()); price = Convert.ToDouble(sr.ReadLine()); inStock = Convert.ToInt32(sr.ReadLine()); Auto temp = new Auto(maker, model, year, price, inStock); temp.calcInventoryCost(); autos[i] = temp; } } } catch (Exception e) { //Handling exceptions Console.WriteLine("The file could not be read:"); Console.WriteLine(e.Message); } } //Method that prints menu options public static int menuOptions() { int option; //Diplay menu Console.WriteLine(" **** MENU **** "); Console.Write(" 1 - Display 2 - Add Auto 3 - SellAuto 4 - SaveExit Your option: "); option = Convert.ToInt32(Console.ReadLine()); //Read option return option; } //Method that displays data available in array public static void displayData(Auto[] autos) {
  • 7. //Looping and printing each auto data for (int i = 0; i < autos.Length; i++) { Console.WriteLine(" "); Console.WriteLine(autos[i].getMaker() + " " + autos[i].getModel() + " " + autos[i].getYear() + " " + autos[i].getPrice() + " " + autos[i].getInStock()); } Console.WriteLine(" "); } //Method that adds auto to file public static void addAuto(Auto[] autos) { int pos = -1; string maker, model; int year, inStock; double price; //Reading data Console.Write(" Input Maker: "); maker = Console.ReadLine(); Console.Write(" Input Model: "); model = Console.ReadLine(); Console.Write(" Input Year: "); year = Convert.ToInt32(Console.ReadLine()); Console.Write(" Input Price: "); price = Convert.ToDouble(Console.ReadLine()); Console.Write(" Input InStock: "); inStock = Convert.ToInt32(Console.ReadLine()); //Getting the position of auto for (int i = 0; i < autos.Length; i++) { if (maker.Equals(autos[i].getMaker())) { pos = i; } } //If auto doesn;t exist
  • 8. if (pos == -1) { //Resize and add new auto Array.Resize(ref autos, (autos.Length + 1)); Auto temp = new Auto(maker, model, year, price, inStock); autos[autos.Length - 1] = temp; Console.WriteLine(" Auto add Success.... "); } else { //If already exists just increment stock autos[pos].setInStock(autos[pos].getInStock() + inStock); Console.WriteLine(" Auto already exist!! Stock updated.... "); } Console.WriteLine(" "); } //Method that sells auto public static void sellAuto(Auto[] autos) { int pos = -1; string maker; //Reading information from user Console.Write(" Input Maker: "); maker = Console.ReadLine(); //Looping and getting data for (int i = 0; i < autos.Length; i++) { if (maker.Equals(autos[i].getMaker())) { pos = i; } } //If auto doesn'e exist if (pos == -1) { Console.WriteLine(" Error!!!! No Auto exists with the given name.... ");
  • 9. } else { //If exits but doesn't have enough stock if ((autos[pos].getInStock()) - 1 < 0) { Console.WriteLine(" Error!!!! Stock not available.... "); } else { //Updating the stock autos[pos].setInStock(autos[pos].getInStock() - 1); Console.WriteLine(" Auto Sale Success.... "); } } } //Method that writes data from array to file public static void saveExit(Auto[] autos) { //Writting data to file using (StreamWriter file = new StreamWriter("C:/AutoData.txt")) { //Fetching data from array and writting to file foreach (Auto auto in autos) { file.WriteLine(auto.getMaker()); file.WriteLine(auto.getModel()); file.WriteLine(auto.getYear()); file.WriteLine(auto.getPrice()); file.WriteLine(auto.getInStock() + 1); } } Console.WriteLine(" Save Success.... "); } } }
  • 10. Solution using System; using System.IO; namespace AutoInventory { //Class that holds the entire information related to Auto class Auto { //Attributes private string maker; private string model; private int year; private double price; private int inStock; private double inventoryCost; public static double totalInventoryCost = 0; //Constructor public Auto(string maker, string model, int year, double price, int inStock) { this.maker = maker; this.model = model; this.year = year; this.price = price; this.inStock = inStock; } //Setter methods public void setMaker(string maker) { this.maker = maker; } public void setModel(string model) { this.model = model; }
  • 11. public void setYear(int year) { this.year = year; } public void setPrice(double price) { this.price = price; } public void setInStock(int stock) { this.inStock = stock; } //Getter Methods public string getMaker() { return maker; } public string getModel() { return model; } public int getYear() { return year; } public double getPrice() { return price; } public int getInStock() { return inStock; } //Readonly Property public double getInventoryCost() {
  • 12. return inventoryCost; } //Method that updates inventory public void calcInventoryCost() { inventoryCost = price * inStock; totalInventoryCost += inventoryCost; } } //Main class class Program { static void Main(string[] args) { //Getting number of autos int count = getCount(); //Creating an array with size obtained Auto[] autos = new Auto[count]; //Loading data loadData(autos); //Displaying and reading menu options int option = menuOptions(); //Loop till user quits while (true) { //Calling appropriate function switch (option) { case 1: displayData(autos); break; case 2: addAuto(autos); break; case 3: sellAuto(autos); break; case 4: saveExit(autos); Environment.Exit(0); break; default: Console.WriteLine(" Invalid Option.... "); break; } option = menuOptions(); }
  • 13. } //Function that fetches the number of autos from file public static int getCount() { int count=0; try { // Create an instance of StreamReader to read from a file. // The using statement also closes the StreamReader. using (StreamReader sr = new StreamReader("f://NumofAutos.txt")) { //Reading count value int.TryParse(sr.ReadLine().ToString(), out count); } } catch (Exception e) { //Handling exceptions Console.WriteLine("The file could not be read:"); Console.WriteLine(e.Message); } return count; } //Method that loads data from file to array public static void loadData(Auto[] autos) { int i, length = autos.Length; try { // Create an instance of StreamReader to read from a file. // The using statement also closes the StreamReader. using (StreamReader sr = new StreamReader("f://AutoData.txt")) { string maker, model; int year, inStock; double price;
  • 14. //Reading data from file and storing in array for (i = 0; i < length; i++) { maker = sr.ReadLine().ToString(); model = sr.ReadLine().ToString(); int.TryParse(sr.ReadLine().ToString(), out year); // year = Convert.ToInt32(sr.ReadLine()); double.TryParse(sr.ReadLine().ToString(), out price); //price = Convert.ToDouble(sr.ReadLine()); int.TryParse(sr.ReadLine().ToString(), out inStock); //inStock = Convert.ToInt32(sr.ReadLine()); //Auto temp = new Auto(maker, model, year, price, inStock); //temp.calcInventoryCost(); // Console.WriteLine(maker+", "+ model+", "+ year+", "+ price+", "+ inStock+" "); autos[i] = new Auto(maker, model, year, price, inStock); autos[i].calcInventoryCost(); } } } catch (Exception e) { //Handling exceptions Console.WriteLine("The file AutoData.txt could not be read:"); Console.WriteLine(e.Message); } } //Method that prints menu options public static int menuOptions() { int option; //Diplay menu Console.WriteLine(" **** MENU **** "); Console.Write(" 1 - Display 2 - Add Auto 3 - SellAuto 4 - SaveExit Your option: "); option = Convert.ToInt32(Console.ReadLine()); //Read option return option;
  • 15. } //Method that displays data available in array public static void displayData(Auto[] autos) { //Looping and printing each auto data for (int i = 0; i < autos.Length; i++) { Console.WriteLine(" "); Console.WriteLine(autos[i].getMaker() + " " + autos[i].getModel() + " " + autos[i].getYear() + " " + autos[i].getPrice() + " " + autos[i].getInStock()); } Console.WriteLine(" "); } //Method that adds auto to file public static void addAuto(Auto[] autos) { int pos = -1; string maker, model; int year, inStock; double price; //Reading data Console.Write(" Input Maker: "); maker = Console.ReadLine(); Console.Write(" Input Model: "); model = Console.ReadLine(); Console.Write(" Input Year: "); year = Convert.ToInt32(Console.ReadLine()); Console.Write(" Input Price: "); price = Convert.ToDouble(Console.ReadLine()); Console.Write(" Input InStock: "); inStock = Convert.ToInt32(Console.ReadLine()); //Getting the position of auto for (int i = 0; i < autos.Length; i++) { if (maker.Equals(autos[i].getMaker())) {
  • 16. pos = i; } } //If auto doesn;t exist if (pos == -1) { //Resize and add new auto Array.Resize(ref autos, (autos.Length + 1)); Auto temp = new Auto(maker, model, year, price, inStock); autos[autos.Length - 1] = temp; Console.WriteLine(" Auto add Success.... "); } else { //If already exists just increment stock autos[pos].setInStock(autos[pos].getInStock() + inStock); Console.WriteLine(" Auto already exist!! Stock updated.... "); } Console.WriteLine(" "); } //Method that sells auto public static void sellAuto(Auto[] autos) { int pos = -1; string maker; //Reading information from user Console.Write(" Input Maker: "); maker = Console.ReadLine(); //Looping and getting data for (int i = 0; i < autos.Length; i++) { if (maker.Equals(autos[i].getMaker())) { pos = i; } }
  • 17. //If auto doesn'e exist if (pos == -1) { Console.WriteLine(" Error!!!! No Auto exists with the given name.... "); } else { //If exits but doesn't have enough stock if ((autos[pos].getInStock()) - 1 < 0) { Console.WriteLine(" Error!!!! Stock not available.... "); } else { //Updating the stock autos[pos].setInStock(autos[pos].getInStock() - 1); Console.WriteLine(" Auto Sale Success.... "); } } } //Method that writes data from array to file public static void saveExit(Auto[] autos) { //Writting data to file using (StreamWriter file = new StreamWriter("f://AutoData.txt")) { //Fetching data from array and writting to file foreach (Auto auto in autos) { file.WriteLine(auto.getMaker()); file.WriteLine(auto.getModel()); file.WriteLine(auto.getYear()); file.WriteLine(auto.getPrice()); file.WriteLine(auto.getInStock() + 1); } }
  • 18. Console.WriteLine(" Save Success.... "); } } } changes are made only to the getCount() and loadData() functions