Create:
This class defines an Employee.
Member variables: ID (int), name (string), salary (double)
Member Methods: Constructors, input/output methods that perform I/O for an employee
Create:
This class defines an array of Employees
Member variables: An array of Employee, SIZE (int), currentSize (int)
Member Methods: Constructors, input/output methods, search/insert/delete/update methods.
Not sure exactly how to store 3 Employee variables inside a single array index.
Updated:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication16
{
class Employee
{
protected int id;
protected string name;
protected double salary;
public Employee()
{
}
public Employee(int _id, string nm, double sal)
{
id = _id;
name = nm;
salary = sal;
}
public void PrintEmployee()
{
Console.WriteLine("id: {0}", id);
Console.WriteLine("Name: {0}", name);
Console.WriteLine("Salary: {0}", salary);
}
}
class EmployeeArray : Employee
{
private Employee[] a;
private int currSize;
private const int SIZE = 100;
public EmployeeArray()
: base()
{
}
public EmployeeArray(int s, int _id, string nm, double sal)
: base(_id, nm, sal)
{
a = new Employee[SIZE];
if (s > SIZE)
Console.WriteLine("Array size is overflow!");
else if (s == SIZE)
Console.WriteLine("Array is full.");
else
currSize = s;
}
public void Input()
{
a = new Employee[3];
for (int i = 0; i < currSize; i++)
{
a[i] = new Employee(id, name, salary);
}
}
public void Output()
{
Console.WriteLine("Array is: ");
foreach (Employee x in a)
Console.WriteLine("a[{0}]= {1}", name, x);
}
public int Search(int key)
{
for (int i = 0; i < currSize; i++)
{
//if (a[i] == key)
// return i;
}
return -1;
}
public void Insert()
{
if (currSize == SIZE)
{
Console.Write("Array is full! ");
return;
}
Console.WriteLine("Enter a number to insert: ");
int y = int.Parse(Console.ReadLine());
Console.Write("Enter the index to where it is to insert: ");
int pos = int.Parse(Console.ReadLine());
for (int i = currSize; i > pos; i--)
a[i] = a[i - 1];
//a[pos] = y;
currSize++;
}
public void Delete()
{
if (currSize == 0)
{
Console.WriteLine("Array is empty! ");
return;
}
Console.Write("Delete by value (1) or by index (2): ");
int key = int.Parse(Console.ReadLine());
int pos = -1;
if (key == 1)
{
Console.WriteLine("Enter the number to delete: ");
int d = int.Parse(Console.ReadLine());
pos = Search(d);
while (pos == -1)
{
Console.WriteLine("The number does not exist, enter again: ");
d = int.Parse(Console.ReadLine());
pos = Search(d);
}
}
else if (key == 2)
{
Console.WriteLine("Enter the index to delete from: ");
pos = int.Parse(Console.ReadLine());
while (pos < 0 || pos > currSize)
{
Console.WriteLine("The index is out of range, enter again: ");
pos = int.Parse(Console.ReadLine());
}
}
else
return;
for (int i = pos; i < currSize; i++)
a[i] = a[i + 1];
currSize--;
if (currSize <= 0)
Console.Write("Array is empty! ");
}
public void Update()
{
Console.WriteLine("Enter the index where to update: ");
int pos = int.Parse(Console.ReadLine());
while (pos < 0 || pos >= currSize)
{
Console.WriteLine("The index you entered is not valid, enter again: ");
pos = int.Parse(Console.ReadLine());
}
Console.WriteLine("Enter the new value: ");
int x = int.Parse(Console.ReadLine());
//a[pos] = x;
Console.Write("Update complete! ");
}
}
class Program
{
//static char ShowMenu()
//{
// Console.WriteLine("\nEnter the letter of operation: \n(o)Print, (s)Search, (i)Insertion, (d)Deletion, (u)Update, (e)Exit\n");
// return char.Parse(Console.ReadLine());
//}
static void Main(string[] args)
{
//char sel = ' ';
Console.Write("Enter number of Employees; ");
int i = 0;
int s = int.Parse(Console.ReadLine());
while ( i < s )
{
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("Enter id: ");
int _id = int.Parse(Console.ReadLine());
Console.WriteLine("");
Console.WriteLine("Enter Name: ");
string nm = Console.ReadLine();
Console.WriteLine("");
Console.WriteLine("Enter Salary: ");
double sal = int.Parse(Console.ReadLine());
EmployeeArray arr = new EmployeeArray(s, _id, nm, sal);
i++;
}
}
}
}
This reads like homework but I'll help you out.
You create your employee class with it's three members and methods.
then you create an array of employee objects.
//How Many employee objects do you need. Let's assume 10 for example
int NUM = 10;
Employee[] employees = new Employee[NUM]; // Declare an An array of employee's of length 10 (zero indexed from 0 - 9)
//Assuming you have made Getters and Setters
//Then if you need to access an employee object's member(s)
employees[0].getId(); //get the first employee's id
employees[0].getName(); //get the first employee's name
employees[0].getSalary(); //get the first employee's name
// Or set them like
employees[4].setId(12); //set the fifth employee's id to 12
employees[4].setName("Joe Bloggs"); //set the fifth employee's name to Joe Bloggs
employees[4].setSalary("30000"); //set the fifth employee's salary to 30000
MSDN C# Arrays
MSDN Classes
There are lots of problems with the code you posted. I'm just going to highlight a few issues, especially since this implementing arrays sounds a lot like computer science homework.
EmployeeArray inherits from Employee. Think about the meaning of public and private keywords and base classes.
Your functions all do more than one thing. This really complicates your code, and is going to result in bugs. Focus on straightforward code that does one thing and communicates what it does.
Users could crash your program in several places by entering something other than a number.
Lastly, to directly answer your question, you can access arrays through an index. You can't store three separate Employee objects in the same index. You've accessed array objects in other parts of your code, so it seems like you understand that you can store different values in different indexes.
Related
Below I am trying to create a method that returns a list filled with Five integers, based on userInput. I want to make methods to use inside that method.
Where would I create these methods in the class, to have scope of variables and then use them inside the main method that returns a list?
class UserLists
{
public static List<int> UserFiveList()
{
List<int> userList = new List<int>();
int userPick1 = 0;
int userPick2 = 0;
int userPick3 = 0;
int userPick4 = 0;
int userPick5 = 0;
// method that fills the list
void FillUserFiveList(int pick, int count)
{
do
{
Console.Write("Enter first number between 1-45 : ");
pick = int.Parse(Console.ReadLine());
if (userList.Contains(pick))
Console.WriteLine("You have to enter a unique number");
else if (pick >= 1 && pick <= 45)
{
Console.WriteLine("Adding your first number in the list...");
userList.Add(pick);
}
else
Console.WriteLine("You have to enter a number between 1-45");
} while (userList.Count < count);
}
//end of method
FillUserFiveList(userPick1, 1);
FillUserFiveList(userPick2, 2);
FillUserFiveList(userPick3, 3);
FillUserFiveList(userPick4, 4);
FillUserFiveList(userPick5, 5);
return userList;
}
public static List<int> UserOneList()
{
List<int> userOneList = new List<int>();
do
{
Console.Write("Enter your number between 1-20 : ");
int userPick1 = int.Parse(Console.ReadLine());
if (userPick1 >= 1 && userPick1 <= 20)
{
Console.WriteLine("Adding your only number in the list...");
userOneList.Add(userPick1);
}
else
Console.WriteLine("You have to enter a number between 1-20");
} while (userOneList.Count < 1);
return userOneList;
}
}
In the Main method, in the for loop, if you copy/paste/run whole program in visual, you'll see that i'm trying to end the game. First "if", if the user hasn't guessed; then attempts decrements by one and keeps guessing. The second "else if", if the user has guessed the PCArray, than the game ends and message shows. those work.
But, the first "else if", if the user has exhausted his attempts to guess, and hasn't guessed PCArray, than it should say "oh no, you couldn't guess..." Why is this not working.
I just want it to work so that if:
- user hasn't guessed but still has attempts, attempts decrements by 1 until 0.
- user has guessed the correct number, it says congrats.
- attempts are 0 and user still hasn't guessed number, then show "oh no..." message.
class Program
{
static void Main(string[] args)
{
string name;
Console.WriteLine("**************Let's play Master-Mined**************");
Console.WriteLine();
Console.Write("Please enter your name: ");
name = Console.ReadLine();
Console.WriteLine("Welcome {0}. Have fun!! ", name);
int numberCount = 0;
int difficultyLevel = 0;
int digitNumber = GetRandomNumberCount(numberCount);
Console.Write(digitNumber + " it is. Let's play.");
Console.WriteLine();
int[] PCArray = GenerateRandomNumbers(digitNumber);
Console.WriteLine("A " + digitNumber + "-digit number has been chosen. Each possible digit may be the number 1, 2, 3 or 4.");
Console.WriteLine(" ******");
int difficulty = GetGameDifficulty(difficultyLevel);
int attempts = difficulty * digitNumber;
Console.WriteLine("Enter your guess ({0} guesses remaining)", attempts);
int remaining = attempts;
for (int i = 0; i < attempts; i++)
{
int[] userArray = GetUserGuess(digitNumber);
int hits = CountHits(PCArray, userArray, attempts);
if ((hits != PCArray.Length) && (attempts > 0))
{
remaining--;
Console.WriteLine("Enter your guess ({0} guesses remaining)", remaining);
}
else if ((attempts < 1))
{
Console.WriteLine("Oh no {0}! You couldn't guess the right number.", name);
Console.WriteLine("The correct number is: ");
for (int j = 0; j < PCArray.Length; j++)
{
Console.Write(PCArray[j] + " ");
}
Console.WriteLine("Would you like to play again (Y/N)? ");
}
else if (hits == PCArray.Length)
{
attempts = 0;
Console.WriteLine("You win {0}!", name);
Console.WriteLine("The correct number is:");
for (int j = 0; j < PCArray.Length; j++)
{
Console.Write(PCArray[j] + " ");
}
}
}
Console.ReadLine();
}
public static int GetRandomNumberCount(int numberCount)
{
int number = 0;
do
{
try
{
Console.Write("How many numbers would you like to use in playing the game (4-10)? ");
number = int.Parse(Console.ReadLine());
Console.WriteLine();
}
catch
{
Console.WriteLine("You must pick a number between 4 and 10. Choose again.");
Console.WriteLine();
}
} while ((number < 4) || (number > 10));
return number;
}
public static int GetGameDifficulty(int difficultyLevel)
{
int difficulty = 0;
do
{
try
{
Console.Write("Choose a difficulty level (1=hard, 2=medium, 3=easy): ");
difficulty = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine(" Incorrect entry: Please re-enter.");
}
} while ((difficulty < 1) || (difficulty > 3));
return difficulty;
}
public static int[] GenerateRandomNumbers(int PCSize)
{
int eachNumber;
int[] randomNumber = new int[PCSize];
Random rnd = new Random();
for (int i = 0; i < randomNumber.Length; i++)
{
eachNumber = rnd.Next(1, 5);
randomNumber[i] = eachNumber;
Console.Write(eachNumber);
}
Console.WriteLine();
return randomNumber;
}
public static int[] GetUserGuess(int userSize)
{
int number = 0;
int[] userGuess = new int[userSize];
for (int i = 0; i < userGuess.Length; i++)
{
Console.Write("Digit {0}: ", (i + 1));
number = int.Parse(Console.ReadLine());
userGuess[i] = number;
//Console.Write(number);
}
Console.WriteLine();
Console.Write("Your guess: ");
for (int i = 0; i < userGuess.Length; i++)
{
Console.Write(userGuess[i] + " ");
}
Console.WriteLine();
return userGuess;
}
public static int CountHits(int[] PCArray, int[] userArray, int attempts)
{
int hit = 0;
int miss = 0;
int hits = 0;
for (int i = 0; i < PCArray.Length; i++)
{
if (PCArray[i] == userArray[i])
{
hit = hit + 1;
hits = hit;
}
else
{
miss = miss + 1;
}
}
Console.WriteLine("Results: {0} Hit(s), {1} Miss(es)", hit, miss);
return hits;
}
}
First of all, you should rethink your code, because the flow control is scattered throughout your code. For example, you don't need both attempts and remaining, they control the same thing.
Using two variables to control the same thing is what is causing your problem. The first two ifs in your for should be like this:
if (hits != PCArray.Length && remaining > 1)
and
else if (remaining == 1)
Note I removed the unnecessary parenthesis. With these changes, your application works, although the code is not too pretty.
A simple way of enhancing your code is to first check for the right result, and if it's not, then decrease the attempts variable and finally check for its value. That's why with your code as it is, the if should compare to 1 instead of 0.
The hits variable in your CountHits method is totally unnecessary; you should just return hit. Actually the miss variable can be avoided too, you can calculate it. Also remember to use the ++ operator.
But as I said first, the important thing is not to make it work but to organize your code properly. Later I will post my version.
My version, it's not the most beautiful thing in the world but I didn't want to change much of your code structure:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("************** Let's play Master-Mind **************\n");
string name = GetPlayerName();
do
{
Play(name);
Console.Write("\nWould you like to play again (Y/N)? ");
}
while (Console.ReadLine().ToUpper() == "Y");
}
private static void Play(string name)
{
int numberCount = GetRandomNumberCount();
Console.Write(numberCount + " it is. Let's play.");
Console.WriteLine();
int[] PCArray = GenerateRandomNumbers(numberCount);
Console.WriteLine("A {0}-digit number has been chosen. Each possible digit may be the number 1 to 4.\n", numberCount);
int difficulty = GetGameDifficulty();
bool won = false;
for (int allowedAttempts = difficulty * numberCount; allowedAttempts > 0 && !won; allowedAttempts--)
{
Console.WriteLine("\nEnter your guess ({0} guesses remaining)", allowedAttempts);
int[] userArray = GetUserGuess(numberCount);
if (CountHits(PCArray, userArray) == numberCount)
won = true;
}
if (won)
Console.WriteLine("You win, {0}!", name);
else
Console.WriteLine("Oh no, {0}! You couldn't guess the right number.", name);
Console.Write("The correct number is: ");
for (int j = 0; j < numberCount; j++)
Console.Write(PCArray[j] + " ");
Console.WriteLine();
}
private static string GetPlayerName()
{
Console.Write("Please enter your name: ");
string name = Console.ReadLine();
Console.WriteLine("Welcome, {0}. Have fun!!\n", name);
return name;
}
public static int GetRandomNumberCount()
{
int number;
Console.Write("How many numbers would you like to use in playing the game (4-10)? ");
while (!int.TryParse(Console.ReadLine(), out number) || number < 4 || number > 10)
Console.WriteLine("You must pick a number between 4 and 10. Choose again.");
return number;
}
public static int GetGameDifficulty()
{
int difficulty = 0;
Console.Write("Choose a difficulty level (1=hard, 2=medium, 3=easy): ");
while (!int.TryParse(Console.ReadLine(), out difficulty) || difficulty < 1 || difficulty > 3)
Console.WriteLine("Incorrect entry: Please re-enter.");
return difficulty;
}
public static int[] GenerateRandomNumbers(int PCSize)
{
int eachNumber;
int[] randomNumber = new int[PCSize];
Random rnd = new Random();
Console.Write("PC number: ");
for (int i = 0; i < PCSize; i++)
{
eachNumber = rnd.Next(1, 5);
randomNumber[i] = eachNumber;
Console.Write(eachNumber);
}
Console.WriteLine();
return randomNumber;
}
public static int[] GetUserGuess(int userSize)
{
int number = 0;
int[] userGuess = new int[userSize];
for (int i = 0; i < userSize; i++)
{
Console.Write("Digit {0}: ", (i + 1));
while (!int.TryParse(Console.ReadLine(), out number) || number < 1 || number > 4)
Console.WriteLine("Invalid number!");
userGuess[i] = number;
}
Console.WriteLine();
Console.Write("Your guess: ");
for (int i = 0; i < userSize; i++)
{
Console.Write(userGuess[i] + " ");
}
Console.WriteLine();
return userGuess;
}
public static int CountHits(int[] PCArray, int[] userArray)
{
int hits = 0;
for (int i = 0; i < PCArray.Length; i++)
{
if (PCArray[i] == userArray[i])
hits++;
}
Console.WriteLine("Results: {0} Hit(s), {1} Miss(es)", hits, PCArray.Length - hits);
return hits;
}
}
It does a few more validations and it even actually lets you play again! ;)
So i have a simple program that i have set up to ask the user for an array size then it gets them to enter the elements then prints them, i would like to set up a Queue so it prints a whole of the array, for example.
History
1 2 3 4 //Length of the Array
3 4 5 6 //User Guess for this round
After this every time the user re enters the array that array would show up in the history also.
History
1 2 3 4 //Length of the Array
3 4 5 6 //User Guess for this round
2 6 7 8 //User second input
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Random_test
{
class Program
{
public int n;
public int[] UserArray;
public int i;
public int reEnter;
public int rear = -1;
public int front = -1;
public int[] history;
public void main()
{
Console.WriteLine("Please enter the Length of Your array");
n = Convert.ToInt32(Console.ReadLine());
UserArray = new int[n];
history = new int[n];
do
{
for (i = 0; i < n; i++)
{
Console.WriteLine("Your Elements");
UserArray[i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < n; i++)
{
Console.WriteLine("Your Array: {0} ", UserArray[i]);
}
Console.WriteLine("Would you like to re-enter your array");
reEnter = Convert.ToInt32(Console.ReadLine());
for (i = 0; i < 1; i++)//loop for history
{
insert();
delete();
showHistory();
}
} while (reEnter == 1);
}
public void insert()
{
if (rear == -1)
{
front = 0;
rear++;
history[rear] = UserArray[i];
}
else
{
rear++;
history[rear] = UserArray[i];
}
}
public void delete()
{
if (front == -1)
{
Console.WriteLine("There is no history availible");
}
else
{
front++;
}
}
public void showHistory()
{
if (rear == -1)
{
Console.WriteLine("There is no history availible");
}
else
{
Console.WriteLine("History");
for (int i = 0; i < n; i++)
{
Console.Write(" {0} ");
Console.Write(" - ");
Console.WriteLine(" {0} ", history[i]);
}
}
}
static void Main(string[] args)
{
Program main = new Program();
main.main();
Console.WriteLine("Game Over");
Console.ReadKey();
}
}
}
This was just a quick jot up program as you can see i have attempted to do the Queue, it works but prints only the first element of the User Array each turn. Unfortunately this is where i do not know how implement what i talked about at the start of the post. I would like to stick to this method of creating the Queues, i do not want to use the queue class, the idea is to keep it clean and simple.
Many Thanks.
Sorry for my evil comments before. I think this might suite your level... happy coding.
public class Program
{
static void Main(string[] args)
{
(new Program()).Ask();
}
private void Ask()
{
string history = "";
while (true)
{
Console.Write("Len > ");
int len = int.Parse(Console.ReadLine());
int[] arr = new int[len];
for (int i = 0; i < len; i++)
{
Console.Write("El{0} > ", i);
arr[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine();
string str = string.Join(",", arr);
Console.WriteLine("Arr > {0}", str);
Console.WriteLine("His > {0}", history);
history += string.Format("[{0}] ", str);
Console.WriteLine("Again?");
if (Console.ReadLine().Length == 0)
break;
Console.WriteLine();
}
}
}
My code asks the user to enter a certain amount of students and to enter there name and score depends on how many students there are. My question is, how would I use an if statement to find out the student with the highest score. (C#)
class Class1
{
public void studentCount()
{
int studentcount;
int i;
int x;
string studentname = "";
Console.WriteLine("Enter how many students there are: ");
studentcount = Convert.ToInt32(Console.ReadLine());
{
for (i = 1; i <= studentcount; i++)
{
Console.WriteLine("Enter students name: ");
studentname = Convert.ToString(Console.ReadLine());
Console.WriteLine("Enter students score: ");
x = Convert.ToInt32(Console.ReadLine());
}
}
Keep track of the current highest x (student's score) and if a new one that's entered is higher than the last highest, update the last highest score's variable and that student's name. You'll need to use one more variable for this to keep track of the current max score. You can always update the student's name to match the student with the max score. After the loop, you can output that student's score and name.
Respecting your actual code, probably this would suit you well.
int studentcount = 0, i = 0, x = 0, highestScore = 0;
string studentname = "", highestScoreStudentName = "";
Console.WriteLine("Enter how many students there are: ");
studentcount = Convert.ToInt32(Console.ReadLine());
{
for (i = 1; i <= studentcount; i++)
{
Console.WriteLine("Enter students name: ");
studentname = Convert.ToString(Console.ReadLine());
Console.WriteLine("Enter students score: ");
x = Convert.ToInt32(Console.ReadLine());
if (x > highestScore)
{
highestScore = x;
highestScoreStudentName = studentname;
}
}
}
There are many ways to accomplish this. Below are a few ways. Best would be the take advantage of OOP and create classes for what you need to do, but of course there are other ways to do what you want.
Sticking with your current method:
public void studentCount()
{
string highestScoringStudent;
int highestScore = 0;
Console.WriteLine("Enter how many students there are: ");
var studentCount = Convert.ToInt32(Console.ReadLine());
for (var i = 0; i < studentCount; i++)
{
Console.WriteLine("Enter students name: ");
var tempStudent = Convert.ToString(Console.ReadLine());
Console.WriteLine("Enter students score: ");
var tempScore = Convert.ToInt32(Console.ReadLine());
if(tempScore > highestScore)
{
highestScore = tempScore;
highestScoringStudent = tempStudent;
}
}
}
With a dictionary to keep track of your students:
public void StudentCount()
{
var students = new Dictionary<string, int>();
var count = Convert.ToInt32(Console.ReadLine());
for (var i = 0; i < count; i++)
{
Console.WriteLine("Enter Student's Name:");
var name = Console.ReadLine();
Console.WriteLine("Enter Student's Score:");
var score = Convert.ToInt32(Console.ReadLine());
students.Add(name, score);
}
var highestStudent = students.OrderByDescending(x => x.Value).FirstOrDefault()
Console.WriteLine("{0} scored {1}", highestStudent.Key, highestStudent.Value);
}
Using OOP:
public class TestEntry
{
public string StudentName { get; set; }
public int Score { get; set; }
}
public class SomeClass
{
readonly List<TestEntry> _testEntries = new List<TestEntry>();
public void EnterTests()
{
_testEntries.Clear();
var count = Convert.ToInt32(Console.ReadLine());
for (var i = 0; i < count; i++)
{
Console.WriteLine("Enter Student's Name:");
var testEntry = new TestEntry();
testEntry.StudentName = Console.ReadLine();
Console.WriteLine("Enter Student's Score:");
testEntry.Score = Convert.ToInt32(Console.ReadLine());
_testEntries.Add(testEntry);
}
}
public void PrintHighestScoringStudent()
{
var highestTest = _testEntries.OrderByDescending(x => x.Score).FirstOrDefault();
if (highestTest == null)
{
Console.WriteLine("No tests entered.");
return;
}
Console.WriteLine("{0} scored {1}", highestTest.StudentName, highestTest.Score);
}
}
use array [] and sort it then top most value is higher
Everton's solution will work, but I would think that you might be interested in keeping track of all scores. In that case, you could use an Array as suggested, but a better solution is probably to use a SortedList.
SortedList<int> students = new SortedList<int>();
...
for (int i = 0; i < studentcount; i++)
{
Console.WriteLine("Enter students name: ");
studentname = Convert.ToString(Console.ReadLine());
Console.WriteLine("Enter students score: ");
x = Convert.ToInt32(Console.ReadLine());
students.Add(x);
}
int max = students.Last; //Default sorting is low to high,
//though this could be changed if
//you want to look into it.
If you wanted to keep track of scores with respect to the student, you could use a List<Tuple<string, int>>, but without some finagling it would not be possible to sort it. However, using Linq finding the max value is not difficult.
List<Tuple<string, int> >students = new List<Tuple<string, int> >();
...
for (int i = 0; i < studentcount; i++)
{
Console.WriteLine("Enter students name: ");
studentname = Convert.ToString(Console.ReadLine());
Console.WriteLine("Enter students score: ");
x = Convert.ToInt32(Console.ReadLine());
students.Add(studentname, x);
}
int max = students.Max(a => a.Item2).FirstorDefault();
I Have the first part of my code pretty complete and I got the gist of the rest, I'm just not sure how to put it all together. Here is the first part
using System;
namespace ConsoleApplication1
{
class Program
{
public class AccountInfo
{
public int Number { get; set; }
public double Balance { get; set; }
public string LastName { get; set; }
}
static void Main(string[] args)
{
List<AccountInfo> accounts = new List<AccountInfo>();
for (int index = 1; index < 6; index++)
{
AccountInfo acc = new AccountInfo();
Console.Write("Enter account number: " + index.ToString() + ": ");
acc.Number = int.Parse(Console.ReadLine());
Console.Write("Enter the account balance: ");
acc.Balance = double.Parse(Console.ReadLine());
Console.Write("Enter the account holder last name: ");
acc.LastName = Console.ReadLine();
accounts.Add(acc);
}
}
}
}
The second part is to ask the user what they want to do with the arrays
enter an a or A to search account numbers
enter a b or B to average the accounts
enter an x or X to exit program
the search part I can use something like this:
public void search Accounts()
{
for(int x = 0; x < validValues.Lenth; ++x)
{
if(acctsearched == validValues[x])
{
isValidItem = true;
acctNumber = Number[x];
}
}
And I can use a while loop with a bool true/false to close out.
I'm not sure how to get the average balance. I keep getting errors like "can't implicitly change int[] to int"
Any help with this would very much appreciated.
Sounds like you have an List of AccountInfo. Are you able to use LINQ?
To get the average, you can do this with LINQ:
double avg = accounts.Select(x=>x.Balance).Average();
To search for a given acct, you can do something like this:
var foundAcct = accounts.SingleOrDefault(x=>x.Number==someSearchNum);
For this to work(and create methods for these 2 actions), you'd need to move the List<AccountInfo> accounts out of the Main and be declared in the class.
With LINQ, you'll required .NET 3.5 or greater.
using System;
namespace AssignmentWeek3
{
class Accounts
{
// private class members, creating new arrays
private int [] AcctNumber = new int[5];
private double [] AcctBalance = new double[5];
private string [] LastName = new string[5];
public void fillAccounts()//fill arrays with user input
{
int x = 0;
for (int i = 0; i < AcctNumber.Length; i++)
{
Console.Write("Enter account number: ");
AcctNumber[x] = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter account balance: ");
AcctBalance[x] = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter account holder last name: ");
LastName[x] = Convert.ToString(Console.ReadLine());
x++;
}
}
public void searchAccounts() //search account method to be called later in main()
{
int accountNum = 0;
bool isValid = false;
int x = 0;
Console.Write("Please enter account number to search for: ");
accountNum = Convert.ToInt32(Console.ReadLine());
while (x < AcctNumber.Length && accountNum != AcctNumber[x])
++x;
if(x != AcctNumber.Length)
{
isValid = true;
}
if(isValid){
Console.WriteLine("AcctNumber: {0} Balance: {1:c} Acct Holder: {2}", AcctNumber[x], AcctBalance[x], LastName[x]);
}
else{
Console.WriteLine("You entered an invalid account number");
}
}
public void averageAccounts()//averageAccounts method to be store for later use
{
// compute and display average of all 5 bal as currency use length.
int x = 0;
double balanceSum = 0;
double Avg = 0;
for (x = 0; x < 5; x++ )
{
balanceSum = balanceSum + AcctBalance[x];
}
Avg = (balanceSum / x);
Console.WriteLine("The average balance for all accounts is {0:c}", Avg);
}
} //end public class Accounts
class week3_assignment //Main class
{
static void Main()
{
char entry = '0';
//instantiate one new Accounts object
Accounts accounts = new Accounts();
//call class methods to fill Accounts
accounts.fillAccounts();
//menu with input options
bool Exit = false;
while (!Exit)
{
while (entry != 'x' && entry != 'X')
{
Console.WriteLine("*****************************************");
Console.WriteLine("enter an a or A to search account numbers");
Console.WriteLine("enter a b or B to average the accounts");
Console.WriteLine("enter an x or X to exit program");
Console.WriteLine("*****************************************");
entry = Convert.ToChar(Console.ReadLine());
switch (entry) //set switch
{
case 'a':
case 'A':
accounts.searchAccounts();//calls search accounts method
break;
case 'b':
case 'B':
accounts.averageAccounts();//calls average accounts method
break;
case 'x':
case 'X':
(Exit) = true;
break;
default:
Console.WriteLine("That is not a valid input");
break;
}
}
}
}
}
}