Replace a column in Array of Structs - c#

Hey I have an array of structs and i need to create in program way to change the values of the arrays. I tried using things like findindex but it replaced all values (e.g changed all of Mark's into Jack's even though i only want the one specific "Mark" to change.)
What i want to do is make user type the customer number and then change all the values of this array. So if i search and want to edit customernumber[0] i can also change all other values like customersurname[0], customerfornemae[0] and so on. I am posting only the parts of code i think are important but if you guys need any more I' can easily provide.
struct customer
{
public int customernumber;
public string customersurname;
public string customerforname;
public string customerstreet;
public string customertown;
public DateTime customerdob;
}
static void Main(string[] args)
{
customer[] customerdetails = new customer[99];
int selector = 0;
int selector2 = 0;
string vtemp = "";
string ctemp = "";
int searchnumber;
int updatenumber;
string searchforename;
string searchsurname;
string searchtown;
DateTime searchdob;
customer resultnumber;
customer resultforename;
customer resultsurname;
customer resulttown;
customer resultdob;
customer updaterenumber;
if (selector == 3)
{
Console.Clear();
Console.WriteLine("Enter the customer number you wish to update: ");
updatenumber = int.Parse(Console.ReadLine());
updaterenumber = Array.Find(customerdetails, customer => customer.customernumber == updatenumber);
}

Related

Calling a variable have user input from a different method

i have fixed the question:
The code is working until it hit the MultyMethod it stop because i have tried to take the output from the SumMethod and do another calculation in the MultyMethod.
So my question is i have tried to use the same input from SumMethod in the MultyMethod but it does not work well i have used all the reference in my mind or i could think of but still it told me : the name "SumMethod" need a reference to call it or you forgetting to use a reference. So how i could use the same input from the SumMethod in the MultyMethod!!
using System;
namespace example
{
class Program
{
public int number1 { set; get; }
public int number2 { set; get; }
public int sum { set; get; }
public int multy { set; get; }
static void Main(string[] args)
{
var value = SumMethod();
var values = MultyMethod();
ResultMethod(value.number1, value.number2, value.sum, values.multy);
}
public static Program SumMethod()
{
var input = new Program();
int i = 0;
Console.WriteLine(" Please Enter your first number: ");
input.number1 = int.Parse(Console.ReadLine());
Console.WriteLine(" Please Enter your second number: ");
input.number2 = int.Parse(Console.ReadLine());
int[] arr = new int[] { input.number1, input.number2 };
do
{
input.sum += arr[i];
i++;
} while (i < 2);
return input;
}
public static Program MultyMethod()
{
var input = new Program();
// here is the issue i am trying to get the input from the previous method instead of asking the user to input the numbers again
// i have tried this
//input.number1 = new input.SumMethod();
// and also have tried to use this reference
//value.SumMethod(); // since the inputs store in this variable but it does not make since to call it this way ><
// i have also tried to use this way
//input.number1 = new SumMethod();
return input;
}
public static void ResultMethod(int number1, int number2, int sum, int multy)
{
Console.WriteLine(" The first number is: ");
Console.WriteLine(number1);
Console.WriteLine(" The second number is: ");
Console.WriteLine(number2);
Console.WriteLine(" The sum of the number is: ");
Console.WriteLine(sum);
Console.WriteLine(" The multiplication of the numbers is: ");
Console.WriteLine(multy);
}
}
}
Okay, your basic problem is that the variable input, which you wish to reference in MultyMethod, is internal to SumMethod. Therefore, MultyMethod can't access it.
You define another variable called input in MultyMethod, but that is NOT the same variable. It's a separate one, the scope of which is just MultyMethod, and can't be accessed outside of it.
So, how to do what you want. I hope you don't mind that I'm also going to make some suggestions about how you could better organize this code.
First, you could define input outside of SumMethod, as a class-level static variable. In that case, it could be accessed by both SumMethod and MultyMethod. The following is a short excerpt (with some lines removed to save space):
class Program
{
public int number1 { set; get; }
public int number2 { set; get; }
public int sum { set; get; }
public int multy { set; get; }
public static Program input = null;
static void Main(string[] args)
{
// etc.
}
public static Program SumMethod()
{
input = new Program();
// rest of the code
return input;
}
public static Program MultyMethod()
{
input = Program.input; // this is a static reference.
// desired multiplication code
return input;
}
Another option would be to parameterize MultyMethod so it takes a Program as a parameter, representing the input:
public static Program MultyMethod(Program input)
{
// You probably don't want to have the same variable have both your sum
// and your multiplication results.
Program newVar = new Program() { number1 = input.number1, number2 = input.number2 };
// Do things with newVar in place of "input"
return newVar;
}
Then you'd change Main to look like this:
var value = SumMethod();
var values = MultyMethod(value);
An even better version would separate getting the input from performing the summing. So you could do this:
static void Main(string[] args)
{
var input = GetInput();
var value = SumMethod(input);
var values = MultyMethod(input);
// do other things
}
Finally, the whole thing would be better if you had separate classes for all three of the following:
The program itself
The input parameters and results
The multiplication and sum methods

how to get employee using optimal way by id,name ,exp

i have written below code without applying any design pattern,Is anything wrong in this code.
class Employee {
public int EmployeeID
{ get; set; }
public int YearOExperience
{ get; set; }
public int Salary
{ get; set; }
public string EmploeyeeType
{ get; set; }
}
interface IEmployee {
List<Employee> getInformation(int id, int exp, int sal);
}
class EmployeeData1 {
public List<Employee> GetData(int id,int exp , int sal)
{
List<Employee> empInfo = new List<Employee> {
new Employee { EmploeyeeType = "P", EmployeeID = 1, Salary = 20000, YearOExperience= 2 },
new Employee { EmploeyeeType = "P", EmployeeID = 2, Salary = 20000, YearOExperience= 2 },
new Employee { EmploeyeeType = "C", EmployeeID = 3, Salary = 20000, YearOExperience= 2 }
};
return empInfo;
}
}
static void Main(string[] args) {EmployeeData1 emp = new EmployeeData1();
emp.getInformation(1, 2, 2000);
};
}
Here is the assignment:
Since you pasted the image instead of text, we have to pay for it by re-typing.
Do not handover like this. Instead of trying to employ design patterns (which is not expected from you), handover work which is correct.
Your assignment says that you should take as input the employee name, employee type and years of experience.
Your console app should get these three values by Console.ReadLine() commands.
Please make sure that this is so. Bu it probably is, since all the code competitions use stdin (Console.ReadLine() reads from stdin) to feed input to an application.
Then, what your teacher wants from you are:
Generate a sequential employee Id,
Calculate the salary according to the years of experience
Print out the results (using Console.WriteLine(), which writes to the stdout (standard output))
Proceed to the next employee
Here is a limited example to help you. Please do research and fill in the required parts yourself, otherwise, what does it mean to get a good mark if it isn't yours?
I am not saying that you can handover this directly, mind you.
But at least you can take this as a starting point.
Good luck.
static void Main()
{
// this will be used to create sequential employee Ids
int employeeId = 0;
while(true) // Just press enter without entering anything to exit.
{
string employeeName = Console.ReadLine();
if(employeeName == "")
{
return;
}
// Get the other two input parameters like the one above.
// Please be careful with the last one (years of experience)
// It should be parsed to an integer (a little research effort)
// string employeeType = ..
// int yearsOfExperience = ..
// Now, assign this employee the next Id.
employeeId++;
// And now, calculate the employee's salary
// You should use the years of experience and employee type
// to match an amount in the salary table.
int salary;
if(employeeType == "Permanent")
{
salary = ..;
}
else
{
salary = ..;
}
// And finally, print-out using stdout
Console.WriteLine("Employee ID: {0}", employeeId);
// Print the other two outputs like the one above
}
}

Multidimensional Array for students and grades

I am not sure if multidimensional arrays would be the correct thing for what I want to do.
I want to input the amount of students and then for each of them I input 5 grades. After doing so I must calculate the average.
So essentially something like this:
Student..........Grade 1......Grade 2......Grade 3......Grade 4......Grade 5......Average
Student1............87..............71................64...............89...............78..............77.8
Student2............54..............76................89...............89...............78..............77.2
I apologise for the formatting. I don't know block quotes to well.
I am not sure if multidimensional arrays would help. Any Ideas.
what you can do is to create a Student class and make an array of Student e.g.
public class Student
{
private ArrayList grades;
public Student()
{
grades = new ArrayList();
}
public void addGrade(double val)
{
grades.Add(val);
}
public double getAverage()
{
double avg = 0;
for (int i = 0; i < grades.Count; i++)
avg += (double)grades[i];
avg /= grades.Count;
return avg;
}
}
and make an array of Student class as:
Student [] students = new Student[10];
add student grades as:
students[0].addGrade(75);
Since the datatype of a student's name is probably a string and the datatype of a student's grades is probably a list of double, I recommend you start with a class that represents a single student. Then, as you gather one student's data from a form, you can create a student object, load the object with data from a form, then calculate the average grade for the student. I'm not sure if you need to do anything with the student object after that (i.e., add it to a list for export, write it to a database, etc., etc.)
The code below only suggests what the student class might look like.
using System.Collections.Generic;
using System.Windows.Forms;
namespace sandbox
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
class Student
{
string studentFirstMiddleLastName;
IList<double> allStudentGrades = new List<double>();
public Student(string studentFirstMiddleLastName, IList<double> allStudentGrades)
{
StudentFirstMiddleLastName = studentFirstMiddleLastName;
AllStudentGrades = allStudentGrades;
}
public string StudentFirstMiddleLastName { get => studentFirstMiddleLastName; set => studentFirstMiddleLastName = value; }
public IList<double> AllStudentGrades { get => allStudentGrades; set => allStudentGrades = value; }
public double CalculateAverageofAllStudentGrades()
{
double average = 0.0;
// add up all grades in AllStudentGrades, divide by number of items in AllStudentGrades, load result of this calculation into the variable `average`
return average;
}
}
}

Creating multiple inputs to a ClassList

So I have coded for a while I C# and learned the basics, one thing that always stops me is how I can create a class and then use a list for a user to input values.
I don't know if I'm totally off the chart with this code, the problem is that I don't understand why I can't use my newly created object of the class and add input to it. All help is appreciated
class Program
{
static void Main(string[] args)
{
List<Citizen> listOfCitizens = new List<Citizen>();
for (int i = 0; i < listOfCitizens.Count; i++)
{
Console.WriteLine("Enter Surname for the citizen:");
listOfCitizens.SurName.add = Console.ReadLine();
Console.WriteLine("Enter Lastname for the citizen:");
listOfCitizens.Lastname.add = Console.ReadLine();
Console.WriteLine("Enter age of the citizen:");
listOfCitizens.age.add = int.Parse(Console.ReadLine());
}
Console.WriteLine($"Name {Citizen.SurName} {Citizen.LastName} {Citizen.age}");
Console.Read();
}
}
class Citizen
{
public static string SurName{ get; set; }
public static string LastName{get;set;}
public static int age { get; set; }
}
A list of something is not a something. Just like a basket of apples is not an apple. You don't eat the basket, you eat an item from the basket.
So when you create your list:
List<Citizen> listOfCitizens = new List<Citizen>();
You would then create an item to add to the list:
Citizen someCitizen = new Citizen();
someCitizen.SurName = "Smith";
// etc.
And then add it to the list:
listOfCitizens.Add(someCitizen);
Additionally, your Citizen is a little off. Those properties shouldn't be static. Not sure why you made them that way, but you should remove the static keyword from everything in your Citizen class.

Array.find() provides strange results

I am in middle of writing an assignment for my part time programming course. The issues with my code is the array.find() and results of that search. It should(In my theory) search the array for information and then post them to the user, however what comes out from all of the searches is the same thing: ass2task1.Program+customer Here are only parts of the code becouse out teacher told us we can post question on the internet as long as we don't post our entire codes
struct customer
{
public int customernumber;
public string customersurname;
public string customerforname;
public string customerstreet;
public string customertown;
public DateTime customerdob;
}
static void Main(string[] args)
{
customer[] customerdetails = new customer[99];
int selector = 0;
int selector2 = 0;
string vtemp = "";
string ctemp = "";
int searchnumber;
string searchforename; //variable/ array declaring
string searchsurname;
string searchtown;
DateTime searchdob;
customer resultnumber;
customer resultforename;
customer resultsurname;
customer resulttown;
customer resultdob;
if (selector2 == 2)
{
Console.Clear();
Console.WriteLine("Enter the forename you are looking for: ");
searchforename = (Console.ReadLine());
resultforename = Array.Find(customerdetails, customer => customer.customerforname == searchforename);
Console.Clear();
Console.WriteLine("Enter the surname you are looking for: "); // all of the searches comes out with ass2task1.Program+customer result
searchsurname = (Console.ReadLine());
resultsurname = Array.Find(customerdetails, customer => customer.customersurname == searchsurname);
Console.WriteLine("The forename resuts:" + resultforename);
Console.WriteLine("The surname resuts:" + resultsurname);
Array.Find() will return the object that matches a predicate, if you want the property value, you would need to do something like: resultforename.customerforname or something similar.
If it is not found, then a default value will be returned, so check for nulls etc.
When you convert an object to a string ("The forename resuts:" + resultforename) it calls the objects ToString() method. Define an appropriate ToString() method:
struct customer
{
public int customernumber;
public string customersurname;
public string customerforname;
public string customerstreet;
public string customertown;
public DateTime customerdob;
public override string ToString()
{
return customersurname + ", " + customerforname;
}
}
To (attempt to) expand on Ric and clcto's answers. The reason you're getting the struct name in your
Console.WriteLine("The forename resuts:" + resultforename);
Console.WriteLine("The surname resuts:" + resultsurname);
Your resultforename is of struct customer - by default Console.WriteLine(struct) does not know how to represent a complex object as a string.
As suggested you could do
Console.WriteLine("The forename resuts:" + resultforename.customerforname);
Or provide your own .ToString() method for the struct as clcto pointed out - doing this you're basically telling Console.WriteLine (or any string representation) how to represent a struct of customer as string.
Don't know if this will help, or make it even less clear. But given:
public struct Foo
{
public string Bar { get; set; }
}
public struct FooTwo
{
public string Bar { get; set; }
public override string ToString()
{
return "This is how to represent a Foo2 as string: " + Bar;
}
}
Foo[] foos = new Foo[99];
Foo foundFoo = foos[0]; // This is equivalent to your find statement... setting a foundFoo local variable to a Foo struct
string foundBar = foos[0].Bar; // This is another way to get to what you're trying to accoomplish, setting a string value representation of your found object.
Console.WriteLine(foundFoo); // Doesn't know how to deal with printing out a Foo struct - simply writes [namespace].Foo
Console.WriteLine(foundFoo.Bar); // Outputs Foo.Bar value
Console.WriteLine(foundBar); // Outputs Foo.Bar value
FooTwo foo2 = new FooTwo();
foo2.Bar = "test bar";
Console.WriteLine(foo2); // outputs: "This is how to represent a Foo2 as string: test bar"

Categories

Resources