How To Read Data Into A List Structure in C#? - c#

I am writing a program that uses a StudentStruct (structure) that consists of: studentID, studentName, and grades (which is a separate List). The program is supposed to read in a sequential text file and contains methods that allow the user to: Add Student, Add Grades (to a particular student), Change Student Name, and Delete Student. At the end of the program it is supposed to overwrite the previous file with the new changes made from the current program session.
My question is how do I read in data from the text file into the separate structure variables within the lists?
My text file looks like this:
00000,Mimzi Dagger,100,50,75,70,45,10,98,83
00001,Alexander Druaga,89,45,80,90,15,73,99,100,61
00002,Nicholas Zarcoffsky,100,50,80,50,75,100,100
00003,Kantmiss Evershot,50,100
Once the structure variables within the list are filled, how do I overwrite the file with the contents of the List structure in the same format as the above file?
Since I have multiple and varying amounts of grades, how would I achieve looping through and adding each grade to the grades list?
As you can maybe already tell, I am very new to c# and this is my first project. Any help would be greatly appreciated!
class Program
{
static string pathSource = #"C:\schoolfiles\StudentGrades.txt";
struct StudentStruct
{
public string studentID;
public string studentName;
public List<string> grades;
}
static void Main(string[] args)
{
StudentStruct student = new StudentStruct();
List<StudentStruct> myList = new List<StudentStruct>();
student.grades = new List<string>();
}
UPDATE: Here is what I have come up with so far:
for (int i = 0; i < fileLines.Length; i++)
{
output = fileLines[i];
string[] outputArray = output.Split(',');
student.grades = new List<string>();
student.studentID = outputArray[0];
student.studentName = outputArray[1];
for (int j = 2; j < outputArray.Length; j++)
{
student.grades.Add(outputArray[j]);
}
myList.Add(student);
UPDATE: The code above worked out wonderfully. Here is the top part of my code involving this question:
static void Main(string[] args)
{
//Declare variables
string output;
//Read the File into an array
string[] fileLines = File.ReadAllLines(PathSource);
StudentStruct student = new StudentStruct();
List<StudentStruct> myList = new List<StudentStruct>();
for (int i = 0; i < fileLines.Length; i++)
{
output = fileLines[i];
string[] outputArray = output.Split(',');
student.grades = new List<string>();
student.studentID = outputArray[0];
student.studentName = outputArray[1];
for (int j = 2; j < outputArray.Length; j++)
{
student.grades.Add(outputArray[j]);
}
myList.Add(student);
}
MainMenu(myList);
}
And then to add the list back to the file I did this:
static void ExitModule(List<StudentStruct> myList)
{
//Declare variables
string inputChoice = null;
string output = null;
System.IO.StreamWriter file = new System.IO.StreamWriter(PathSource);
Console.Clear();
Console.WriteLine("Are You Sure You Want To Exit The Program? Y/N");
inputChoice = Console.ReadLine();
if (inputChoice == "Y" || inputChoice == "y")
{
for (int i = 0; i < myList.Count; i++)
{
output = (myList[i].studentID + "," + myList[i].studentName);
for (int j = 0; j < myList[i].grades.Count; j++)
{
output += ("," + myList[i].grades[j]);
}
file.WriteLine(output);
}
file.Close();
Environment.Exit(0);

Since this is clearly homework, it may be a good time for you to learn about data structures. This will help you store the information you've read in from the text file efficiently, allowing you to write it out much more easily after modifying the records.
Here are a couple of other random pointers:
The System.IO.File.ReadLines(pathSource) method would be a good place to start reading each line of a text file
You should almost never be using a struct in C# (especially one that is mutable like in your example) unless you are well-versed in its semantics and purpose. Use a class instead

try this code. it's working for me
class Program
{
static string pathSource = #"C:\schoolfiles\StudentGrades.txt";
struct StudentStruct
{
public string studentID;
public string studentName;
public List<string> grades;
}
static void Main(string[] args)
{
StudentStruct student = new StudentStruct();
List<StudentStruct> myList = new List<StudentStruct>();
student.grades = new List<string>();
// get all lines from text file
string[] allLinesFromFile = File.ReadAllLines(pathSource);
// iterate through each line and process it
foreach(string line in allLinesFromFile)
{
// split each line on ','
string[] sections = line.Split(',');
student.studentID = sections[0];
student.studentName = sections[1];
// use this loop to add numbers to list of grades
for(int i =2; i < sections.Length; i++)
{
student.grades.Add(sections[i]);
}
// add this student to list
myList.Add(student);
// create new object of student
student = new StudentStruct();
student.grades = new List<string>();
}
}

A few things.
(1) I am not sure why your teacher/professor would have you use a struct here. A class is much more appropriate. I actually cringed when I first saw the code
(2) having something as a const also implies that it is static "pathSource"
(3) Properties should be capitalized "pathSource" -> "PathSource"
(4) You should separate responsibilities... Try not to put everything in Main
(5) You shouldn't have to create an instance of grades outside of StudentStruct, this can lead to errors. i.e. NullPointerException... basically the struct should be self containing.
(6) Everything should compile. I haven't tested it. If you have any issues. let me know.
Program {
private const string PathSource = #"C:\schoolfiles\StudentGrades.txt";
private struct StudentStruct
{
public string StudentID;
public string StudentName;
private List<string> _gradeList;
public List<string> GradeList
{
// if _gradeList is null create a new instance
get { return _gradeList ?? (_gradeList = new List<string>()); }
private set { _gradeList = value; }
}
}
private static void Main( string[] args )
{
var studentFile = File.ReadAllLines( PathSource );
// If you haven't learned about delegates or extensions methods...
// You can just change it to a foreach statement
var myList = studentFile.Select( GetStudent ).ToList();
// make sure we have everything
foreach (var studentStruct in myList)
{
Console.WriteLine( "{0} {1}", studentStruct.studentName, studentStruct.studentID );
foreach (var grade in studentStruct.GradeList) { Console.Write( grade + " " ); }
Console.WriteLine();
}
}
private static StudentStruct GetStudent( string line )
{
var student = new StudentStruct();
var studentDelimited = line.Split( ',' );
student.studentID = studentDelimited[ 0 ];
student.studentName = studentDelimited[ 1 ];
for ( int i = 2; i < studentDelimited.Length; i++ ) { student.GradeList.Add( studentDelimited[ i ] ); }
return student;
}
}

Related

StreamWriter C# formatting output

Problem Statement
In order to run gene annotation software, I need to prepare two types of files, vcard files and coverage tables, and there has to be one-to-one match of vcard to coverage table. Since Im running 2k samples, its hard to identify which file is not one-to-one match. I know that both files have unique identifier numbers, hence, if both folders have files that have same unique numbers, i treat that as "same" file
I made a program that compares two folders and reports unique entries in each folder. To do so, I made two list that contains unique file names to each directory.
I want to format the report file (tab delimited .txt file) such that it looks something like below:
Unique in fdr1 Unique in fdr2
file x file a
file y file b
file z file c
I find this difficult to do because I have to iterate twice (since I have two lists), but there is no way of going back to the previous line in StreamWriter as far as I know. Basically, once I iterate through the first list and fill the first column, how can I fill the second column with the second list?
Can someone help me out with this?
Thanks
If design of the code has to change (i.e. one list instead of two), please let me know
As requested by some user, this is how I was going to do (not working version)
// Write report
using (StreamWriter sw = new StreamWriter(dest_txt.Text + #"\" + "Report.txt"))
{
// Write headers
sw.WriteLine("Unique Entries in Folder1" + "\t" + "Unique Entries in Folder2");
// Write unique entries in fdr1
foreach(string file in fdr1FileList)
{
sw.WriteLine(file + "\t");
}
// Write unique entries in fdr2
foreach (string file in fdr2FileList)
{
sw.WriteLine(file + "\t");
}
sw.Dispose();
}
As requested for my approach for finding unique entries, here's my code snippet
Dictionary<int, bool> fdr1Dict = new Dictionary<int, bool>();
Dictionary<int, bool> fdr2Dict = new Dictionary<int, bool>();
List<string> fdr1FileList = new List<string>();
List<string> fdr2FileList = new List<string>();
string fdr1Path = folder1_txt.Text;
string fdr2Path = folder2_txt.Text;
// File names in the specified directory; path not included
string[] fdr1FileNames = Directory.GetFiles(fdr1Path).Select(Path.GetFileName).ToArray();
string[] fdr2FileNames = Directory.GetFiles(fdr2Path).Select(Path.GetFileName).ToArray();
// Iterate through the first directory, and add GL number to dictionary
for(int i = 0; i < fdr1FileNames.Length; i++)
{
// Grabs only the number from the file name
string number = Regex.Match(fdr1FileNames[i], #"\d+").ToString();
int glNumber;
// Make sure it is a number
if(Int32.TryParse(number, out glNumber))
{
fdr1Dict[glNumber] = true;
}
// If number not present, raise exception
else
{
throw new Exception(String.Format("GL Number not found in: {0}", fdr1FileNames[i]));
}
}
// Iterate through the second directory, and add GL number to dictionary
for (int i = 0; i < fdr2FileNames.Length; i++)
{
// Grabs only the number from the file name
string number = Regex.Match(fdr2FileNames[i], #"\d+").ToString();
int glNumber;
// Make sure it is a number
if (Int32.TryParse(number, out glNumber))
{
fdr2Dict[glNumber] = true;
}
// If number not present, raise exception
else
{
throw new Exception(String.Format("GL Number not found in: {0}", fdr2FileNames[i]));
}
}
// Iterate through the first directory, and find files that are unique to it
for (int i = 0; i < fdr1FileNames.Length; i++)
{
int glNumber = Int32.Parse(Regex.Match(fdr1FileNames[i], #"\d+").Value);
// If same file is not present in the second folder add to the list
if(!fdr2Dict[glNumber])
{
fdr1FileList.Add(fdr1FileNames[i]);
}
}
// Iterate through the second directory, and find files that are unique to it
for (int i = 0; i < fdr2FileNames.Length; i++)
{
int glNumber = Int32.Parse(Regex.Match(fdr2FileNames[i], #"\d+").Value);
// If same file is not present in the first folder add to the list
if (!fdr1Dict[glNumber])
{
fdr2FileList.Add(fdr2FileNames[i]);
}
I am a quite confident that this will work as I've tested it:
static void Main(string[] args)
{
var firstDir = #"Path1";
var secondDir = #"Path2";
var firstDirFiles = System.IO.Directory.GetFiles(firstDir);
var secondDirFiles = System.IO.Directory.GetFiles(secondDir);
print2Dirs(firstDirFiles, secondDirFiles);
}
private static void print2Dirs(string[] firstDirFile, string[] secondDirFiles)
{
var maxIndex = Math.Max(firstDirFile.Length, secondDirFiles.Length);
using (StreamWriter streamWriter = new StreamWriter("result.txt"))
{
streamWriter.WriteLine(string.Format("{0,-150}{1,-150}", "Unique in fdr1", "Unique in fdr2"));
for (int i = 0; i < maxIndex; i++)
{
streamWriter.WriteLine(string.Format("{0,-150}{1,-150}",
firstDirFile.Length > i ? firstDirFile[i] : string.Empty,
secondDirFiles.Length > i ? secondDirFiles[i] : string.Empty));
}
}
}
It's a quite simple code but if you need help understanding it just let me know :)
I would construct each line at a time. Something like this:
int row = 0;
string[] fdr1FileList = new string[0];
string[] fdr2FileList = new string[0];
while (row < fdr1FileList.Length || row < fdr2FileList.Length)
{
string rowText = "";
rowText += (row >= fdr1FileList.Length ? "\t" : fdr1FileList[row] + "\t");
rowText += (row >= fdr2FileList.Length ? "\t" : fdr2FileList[row]);
row++;
}
Try something like this:
static void Main(string[] args)
{
Dictionary<int, string> fdr1Dict = FilesToDictionary(Directory.GetFiles("path1"));
Dictionary<int, string> fdr2Dict = FilesToDictionary(Directory.GetFiles("path2"));
var unique_f1 = fdr1Dict.Where(f1 => !fdr2Dict.ContainsKey(f1.Key)).ToArray();
var unique_f2 = fdr2Dict.Where(f2 => !fdr1Dict.ContainsKey(f2.Key)).ToArray();
int f1_size = unique_f1.Length;
int f2_size = unique_f2.Length;
int list_length = 0;
if (f1_size > f2_size)
{
list_length = f1_size;
Array.Resize(ref unique_f2, list_length);
}
else
{
list_length = f2_size;
Array.Resize(ref unique_f1, list_length);
}
using (StreamWriter writer = new StreamWriter("output.txt"))
{
writer.WriteLine(string.Format("{0,-30}{1,-30}", "Unique in fdr1", "Unique in fdr2"));
for (int i = 0; i < list_length; i++)
{
writer.WriteLine(string.Format("{0,-30}{1,-30}", unique_f1[i].Value, unique_f2[i].Value));
}
}
}
static Dictionary<int, string> FilesToDictionary(string[] filenames)
{
Dictionary<int, string> dict = new Dictionary<int, string>();
for (int i = 0; i < filenames.Length; i++)
{
int glNumber;
string filename = Path.GetFileName(filenames[i]);
string number = Regex.Match(filename, #"\d+").ToString();
if (int.TryParse(number, out glNumber))
dict.Add(glNumber, filename);
}
return dict;
}

Count the number of words within an Array or List

I need to count the number of words within an array or a list. The reason I say array or list is because I am not sure which would be the best to use in this situation. The data is static and in a .txt file (It's actually a book). I was able to create an array and break down words from the array but for the life of me I can not count! I have tried many different ways to do this and I'm thinking since it is a string it is unable to count. I have even teetered on the edge of just printing the whole book to a listbox and counting from the listbox but, that's ridiculous.
public partial class mainForm : Form
{
//------------------------
//GLOBAL VARIABLES:
//------------------------
List<string> countWords;
string[] fileWords;
string[] fileLines;
char[] delim = new char[] { ' ', ',','.','?','!' };
string path;
public mainForm()
{
InitializeComponent();
}
private void BookTitle() // TiTleAndAuthor Method will pull the Book Title and display it.
{
for (int i = 0; i < 1; i++)
{
bookTitleLabel.Text = fileLines[i];
}
}
private void BookAuthor() // TiTleAndAuthor Method will pull the Book Author and display it.
{
for (int i = 1; i < 2; i++)
{
bookAuthorLabel.Text = fileLines[i];
}
}
private void FirstLines() // FirstTenWords Method pulls the first ten words of any text file and prints the to a ListBox
{
for (int i = 0; i <= 499; i++)
{
wordsListBox.Items.Add(fileWords[i]);
}
}
private void WordCount() // Count all the words in the file.
{
}
private void openFileButton_Click(object sender, EventArgs e)
{
OpenFileDialog inputFile = new OpenFileDialog();
if (inputFile.ShowDialog() == DialogResult.OK) // check the file the user selected
{
path = inputFile.FileName; // save that path of the file to a string variable for later use
StreamReader fileRead = new StreamReader(path); // read a file at the path outlined in the path variable
fileWords = fileRead.ReadToEnd().Split(delim); // Breakdown the text into lines of text to call them at a later date
fileLines = File.ReadAllLines(path);
countWords = File.ReadLines(path).ToList();
wordsListBox.Items.Clear();
BookTitle();
BookAuthor();
FirstLines();
WordCount();
}
else
{
MessageBox.Show("Not a valid file, please select a text file");
}
}
}
Maybe this is useful:
static void Main(string[] args)
{
string[] lines = File_ReadAllLines();
List<string> words = new List<string>();
foreach(var line in lines)
{
words.AddRange(line.Split(' '));
}
Console.WriteLine(words.Count);
}
private static string[] File_ReadAllLines()
{
return new[] {
"The one book",
"written by gnarf",
"once upon a time ther werent any grammer",
"iso 1-12122-445",
"(c) 2012 under the hills"
};
}
Before I get to the answer, a quick observation on some of the loops:
for (int i = 1; i < 2; i++)
{
bookAuthorLabel.Text = fileLines[i];
}
This'll only run once, so it's pointless to have it in a loop (unless you intended this to actually loop through the whole list, in which case it's a bug). If this is the expected behavior, you might as well just do
bookAuthorLabel.Text = fileLines[1];
You have something similar here:
for (int i = 0; i < 1; i++)
{
bookTitleLabel.Text = fileLines[i];
}
Again, this is pointless.
Now for the answer itself. I'm not sure if you're trying to get total word count or count of individual words, so here's a code sample for doing both:
private static void CountWords()
{
const string fileName = "CountWords.txt";
// Create a dummy file
using (var sw = new StreamWriter(fileName))
{
sw.WriteLine("This is a short sentence");
sw.WriteLine("This is a long sentence");
}
string text = File.ReadAllText(fileName);
string[] result = text.Split(new[] { " ", Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
// Total word count
Console.WriteLine("Total count: " + result.Count().ToString());
// Now to illustrate getting the count of individual words
var dictionary = new Dictionary<string, int>();
foreach (string word in result)
{
if (dictionary.ContainsKey(word))
{
dictionary[word]++;
}
else
{
dictionary[word] = 1;
}
}
foreach (string key in dictionary.Keys)
{
Console.WriteLine(key + ": " + dictionary[key].ToString());
}
}
This should be easy to adapt to your particular needs in this case.
Read text file line by line. split by empty character and remove unnecessary spaces. sum this count to total.
var totalWords = 0;
using (StreamReader sr = new StreamReader("abc.txt"))
{
while (!sr.EndOfStream)
{
int count = sr
.ReadLine()
.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).Count();
totalWords += count;
}
You can also use the below code:
totalWords = fileRead.ReadToEnd().Split(delim, StringSplitOptions.RemoveEmptyEntries).Length;

Cannot permanently replace value in an array

I can't permanently replace the array members. When I change the value of String Clue, the string being displayed only displays the current value of clue. I think the problem us on the initialization of char[]. I tried to put them in other parts of the code but it produces error. Beginner here! Hope you can help me. Thanks! :)
private void clues(String clue)
{
int idx = numb[wordOn]+4;
char[] GuessHide = Words[idx].ToUpper().ToCharArray();
char[] GuessShow = Words[idx].ToUpper().ToCharArray();
for (int a = 0; a < GuessHide.Length; a++)
{
if (GuessShow[a] != Convert.ToChar(clue.ToUpper()))
GuessHide[a] = '*';
else
GuessHide[a] = Convert.ToChar(clue.ToUpper());
}
Guess(string.Join("", GuessHide));
}
Edited - because you initalize GuessHide at each call of calls in your code and you do not store its current state you basically reset it each time. Still, you can make some small changes in your code like this:
private static void clues(string clue, char[] GuessHide, char[] GuessShow)
{
for (int a = 0; a < GuessHide.Length; a++)
{
if (GuessShow[a] == Convert.ToChar(clue.ToUpper()))
{
GuessHide[a] = Convert.ToChar(clue.ToUpper());
}
}
Console.WriteLine(string.Join("", GuessHide));
}
Call it like this:
clues("p", GuessHide, GuessShow);
clues("a", GuessHide, GuessShow);
Initialise GuessShow and GuessHide in the outside code like this:
char[] GuessHide = new string('*', Words[idx].Length).ToCharArray();
char[] GuessShow = Words[idx].ToUpper().ToCharArray();
public class Program
{
static string[] Words;
static string[] HiddenWords;
public static void Main()
{
Words = new string[] { "Apple", "Banana" };
HiddenWords = new string[Words.Length];
for (int i = 0; i < Words.Length; i++)
{
HiddenWords[i] = new string('*', Words[i].Length);
}
Guess('P', 0);
Guess('a', 0);
Guess('A', 1);
Guess('N', 1);
Console.ReadLine();
}
private static void Guess(char clue, int idx)
{
string originalWord = Words[idx];
string upperedWord = Words[idx].ToUpper();
char[] foundSoFar = HiddenWords[idx].ToCharArray();
clue = char.ToUpper(clue);
for (int i = 0; i < upperedWord.Length; i++)
{
if (upperedWord[i] == clue)
{
foundSoFar[i] = originalWord[i];
}
}
HiddenWords[idx] = new string(foundSoFar);
Console.WriteLine(HiddenWords[idx]);
}
}

Read from file and find max c#

I have started learning c# just over 3 months so for homework I have an exercise where i have to read from a text file with 50 names and marks. I have to find the name with the highest mark display it and save the result to a text file.This is what I have come up with.
namespace FINAL
{
class Program
{
public static string [] parts;
struct StudentDetails
{
public string name;
public string surname;
};
struct CourseWorkResults
{ public int mark;
};
static void Main(string[] args)
{
string [] Lines = System.IO.File.ReadAllLines(#"F:\FINAL\StudentExamMarks.txt");
foreach (string line in Lines)
{
string[] parts = line.Split();
}
StudentDetails[] Student = new StudentDetails[50];
CourseWorkResults[] Results = new CourseWorkResults[50];
GetName( ref Student ,ref parts );
FindMark ( ref Results , parts);
FindMax (ref Results);
}
static void GetName(ref StudentDetails[]Student, ref string[] parts)
{
for (int i = 0; i < Student.Length; i++ )
{
Student[i].name = parts[0];
Student[i].surname = parts[1];
}
}
static void FindMark ( ref CourseWorkResults[]Results, string [] parts )
{
for (int i=0; i< Results.Length;i++)
{
Results[i].mark = Convert.ToInt16(parts[2]);
}
}
static void FindMax( ref CourseWorkResults[]Results)
{
for (int i = 0; i < Results.Length; i++)
{
int max = 0;
max = Results[2].mark;
if (Results[i].mark > max)
{
max = Results[i].mark;
}
}
}
static void DisplayResults( ref CourseWorkResults[]Results, StudentDetails[]Student, int max)
{
Console.WriteLine(" The student with the highest score is {0} {1} :{2}", Student[0].name, Student[1].surname, max);
}
}
}
My problem is the GetName procedure , I can't pass by reference parts. What am I doing wrong?
The problem here is that a struct is an immutable value type. So when you write :
Student[i].name = parts[0];
You are just trying to modify a local a copy of Student[i]. Actually, each time you trying to access Student[i], it will always return a copied value instead the instance on the list.
A workaround is to have StudentDetails as class instead of struct
class StudentDetails
{
public string name;
public string surname;
};
The issue applies also for CourseWorkResults struct.
In addition, as arrays are already reference in .NET. You don't really need to pass it as reference unless you want it to reference another object. I.e, this :
static void GetName(StudentDetails[]Student, ref string[] parts)
{
for (int i = 0; i < Student.Length; i++ )
{
Student[i].name = parts[0];
Student[i].surname = parts[1];
}
}
will work as
static void GetName(ref StudentDetails[]Student, ref string[] parts)
{
for (int i = 0; i < Student.Length; i++ )
{
Student[i].name = parts[0];
Student[i].surname = parts[1];
}
}
Unless you add something like this:
static void GetName(ref StudentDetails[]Student, ref string[] parts)
{
Student = anotherStudentArray ; // Here the ref param is really needed as you want to reassign Student to a new array instance
for (int i = 0; i < Student.Length; i++ )
{
Student[i].name = parts[0];
Student[i].surname = parts[1];
}
}

Array of Structs | Not passing values

I am new to structs in C# and I am stuck and can not pass the values in a file back to struct and successfully read them again.
The initialisation values work fine, but the file will not load at all
This is what I have so far:
public struct Card
{
public char suit;//'C'- Clubs, 'D'-Diamonds,'H'- Hearts
//and 'S'- Spades
public int value;//2-14 – for 2-10, Jack, Queen, King, Ace
}
static void Main(string[] args)
{
const int CARDS_IN_HAND = 5;//number of cards in hand
Card[] hand = new Card[CARDS_IN_HAND];//array of cards
InitialiseArray(hand);
Console.WriteLine("-------------\n");
Console.WriteLine("Initialised Values in Array");
DisplayHandData(hand);
Console.ReadLine();
The issue seems to be below
LoadArray(hand);//load values into array for use
//check values loaded to array
Console.WriteLine("-------------\n");
Console.WriteLine("Actuals Values in Array from file");
DisplayHandData(hand);
Console.ReadLine();
}
public static void InitialiseArray(Card[] data)
{
for (int count = 0; count < data.Length; count++)
{
data[count].suit = 'C';
data[count].value = 0;
}
}
public static void LoadArray(Card[] data)
{
string fileName = "FullHouse.txt";//name of file for menu item 3
//data in file = C 13 H 13 D 13 C 10 H 10
string input = fileName;
List<Card> cards = new List<Card>();
//string input = fileName;
StreamReader inFile = new StreamReader(fileName);//open file
input = inFile.ReadLine();//priming read for array
string[] inputArray = input.Split(new char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
//input loading data into array
for (int i = 0; i < 10; i += 2)
{
Card newCard = new Card();
newCard.suit = inputArray[i][0];
newCard.value = int.Parse(inputArray[i + 1]);
cards.Add(newCard);
}
inFile.Close();
}
public static void DisplayHandData(Card[] data)
{
Console.WriteLine();
//test values loaded into array in correct positions
for (int records = 0; records < data.Length; records++)
{
Console.WriteLine(data[records].suit);
Console.WriteLine(data[records].value);
}
Console.WriteLine("-------------\n");
Console.ReadLine();
}
Any help would be greatly appreciated.
Your LoadArray should work just fine. The problem is probably that you are filling in variable cards, which is a local List<Card>, but what you probably want to do is fill in the data parameter.
Here is my sugestion for altering the for-cycle in LoadArray method
for (int i = 0; i < data.Length; ++i)
{
Card newCard = new Card();
newCard.suit = inputArray[i * 2][0];
newCard.value = int.Parse(inputArray[i * 2 + 1]);
data[i] = newCard;
}
But be careful about this approach. It is quite fragile. If there will be a mismatch in the length of data and inputArray, you will get an exception (if inputArray will be shorter than expected). You should check the length before the for-cycle.
Your LoadArray() method isn't changing the contents of the array passed in to it.
I recommend using a List in your main method instead, and change LoadArray() to:
public static List<Card> LoadArray()
{
string fileName = "FullHouse.txt";//name of file for menu item 3
//data in file = C 13 H 13 D 13 C 10 H 10
string input = fileName;
List<Card> cards = new List<Card>();
//string input = fileName;
StreamReader inFile = new StreamReader(fileName);//open file
input = inFile.ReadLine();//priming read for array
string[] inputArray = input.Split(new char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
//input loading data into array
for (int i = 0; i < 10; i += 2)
{
Card newCard = new Card();
newCard.suit = inputArray[i][0];
newCard.value = int.Parse(inputArray[i + 1]);
cards.Add(newCard);
}
inFile.Close();
return cards;
}
Then you shouldn't need the InitialiseArray() method at all.
Instead you can do:
var hand = LoadArray();
Of course, then you might want to rename LoadArray() to something like LoadHand().
You can check, the value using Console.WriteLine(hand.Count) this will give you the size, and you can display your data in hand some like this
foreach(var h in hand)
{
Console.WriteLine(h.suit);
Console.WriteLine(h.value);
}
if you wish you can try this too.
hand.ForEach(h=>
{
Console.WriteLine(h.suit);
Console.WriteLine(h.value);
});
Edited:
Sorry, Matthew; I should put this as a comment under your answer. :-)

Categories

Resources