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();
Related
Simple console app that takes user input into a multidimensional array as students, and scores. Having trouble getting the entered scores from the loop, into the array. Do I need a nested loop?
Console.WriteLine("How many students will you be grading?");
string totalStudents = Console.ReadLine();
int studentSum = Convert.ToInt32(totalStudents);
Console.WriteLine(string.Empty);
Console.WriteLine("How many test scores will you enter for each student?");
string totalScores = Console.ReadLine();
int scoreSum = Convert.ToInt32(totalScores);
int[,] studentScores = new int[studentSum, scoreSum];
Console.WriteLine(string.Empty);
for (int scoreIndex = 0; scoreIndex < scoreSum; scoreIndex++)
{
Console.WriteLine("Enter score");
var score = Console.ReadLine();
Console.WriteLine(string.Empty);
int parsedScore = 0;
success = int.TryParse(score, out parsedScore);
studentScores[scoreSum] = parsedScore;
}
You would need another loop around like
for (int scoreIndex = 0; scoreIndex < studentSum; scoreIndex++)
{
for(int j=0; j<studentSum; j++)
{
Console.WriteLine("Enter score");
var score = Console.ReadLine();
Console.WriteLine(string.Empty);
int parsedScore = 0;
success = int.TryParse(score, out parsedScore);
studentScores[scoreIndex,j] = parsedScore;
}
}
I need help writing a program that takes in student info for three separate fields (ID Number, first name, last name). Then, sorts the table alphabetically based on the last name field. The user will input the student data, then I would like it to separate the last name data into two buckets which will then be put into a bubble sort. I am having trouble with adding the data into separate buckets.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _123_Assignment2
{
using System;
using static System.Console;
class Program
{
struct student
{
public int studentId;
public string firstName;
public string lastName;
};
static void Main(string[] args)
{
student[] studentInfo = new student[20];
string[] bucketLow = new string[0];
string[] bucketHigh = new string [0];
int x = 0;
int y = 0;
WriteLine("Enter student ID number:");
studentInfo[x].studentId = Convert.ToInt32(ReadLine());
while (studentInfo[x].studentId != 999)
{
WriteLine("Enter first name:");
studentInfo[x].firstName = ReadLine();
WriteLine("Enter last name:");
studentInfo[x].lastName = ReadLine();
x++;
WriteLine("Enter student ID number:");
studentInfo[x].studentId = Convert.ToInt32(ReadLine());
}
for (int j = 0; j < studentInfo.Length; j++)
{
if (studentInfo[j].lastName.CompareTo(studentInfo[j + 1].lastName) > 0)
bucketLow[y] = studentInfo[j].lastName;
else
bucketHigh[y] = studentInfo[j].lastName;
y++;
}
}
}
}
Try this code, you can check my comments for explanation:
student[] studentInfo = new student[20];
//Make sure you initialize the correct number of variables on your string
string[] bucketLow = new string[20];
string[] bucketHigh = new string[20];
int x = 0;
int y = 0;
//I commented out this line since you are already asking for inputs on without going on your counter scenario
//Console.WriteLine("Enter student ID number:");
//studentInfo[x].studentId = Convert.ToInt32(Console.ReadLine());
//I made changes on this line, since, you are doing a condition based on the number of increment on your counter
while (x <= 2)
{
//I put the enter student ID above since it will not be counted if it was put after the counter x
Console.WriteLine("Enter student ID number:");
studentInfo[x].studentId = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter first name:");
studentInfo[x].firstName = Console.ReadLine();
Console.WriteLine("Enter last name:");
studentInfo[x].lastName = Console.ReadLine();
x++;
}
for (int j = 0; j < x; j++)
{
//Make sure you put group all your conditions on round brackets to achieve your desired condition
if ((studentInfo[j].lastName.CompareTo(studentInfo[j + 1].lastName)) > 0)
bucketLow[y] = studentInfo[j].lastName;
else
bucketHigh[y] = studentInfo[j].lastName;
y++;
}
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! ;)
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.
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;
}
}
}
}
}
}