I'm working on an exam app (c# console application)
The app asks the user to enter its name, I would like the app to read in that user's name and
print the user's details based on the details I've stored in the objects
For example:
If the user's name matches the name in this object:
students s3 = new students("Dee", "Scott", "Computing", 100m, 66.6m);
how could it print this user's details.
I've got a separate method that prints out the user's details
public string gradeDetails {
get { return FirstName + LastName + Course + FinalGrade; }
}
I cant figure out how to match the user input to corresponding object.
You can use the Console.Readline() method
public static void Main()
{
string line;
Console.WriteLine("Enter one or more lines of text (press CTRL+Z to exit):");
Console.WriteLine();
do {
Console.Write(" ");
line = Console.ReadLine();
if (line != null)
Console.WriteLine(" " + line);
} while (line != null);
Console.ReadLine();
Console.WriteLine(); or Console.Write();
I am not sure if that is what you are asking, but those are the calls to read and write.
This info is easily Google-able though.
The example below will do what you asked for. If you have any questions regarding the code I used then don't hesitate to ask.
class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Course { get; set; }
public decimal FinalGrade { get; set; }
public Student(string firstName,
string lastName,
string course)
{
FirstName = firstName;
LastName = lastName;
Course = course;
FinalGrade = 0;
}
// This will first call the constructor above and then continue.
public Student(string firstName,
string lastName,
string course,
decimal finalGrade) : this(firstName, lastName, course)
{
FinalGrade = finalGrade;
}
// By overriding ToString we can use Console.WriteLine(student) directly.
public override string ToString()
{
return string.Format(#"FirstName: {0}, LastName: {1}, Course: {2}, FinalGrade: {3}",
FirstName,
LastName,
Course,
FinalGrade);
}
}
class Program
{
static void Main(string[] args)
{
// Create our students.
List<Student> students = new List<Student>
{
new Student("John", "Test", "Computing"),
new Student("Tim", "Test", "Computing", 8.25m)
};
string user = "";
do
{
Console.Clear();
Console.WriteLine("Please enter the name of the student:");
user = Console.ReadLine();
if (user.Equals("exit", StringComparison.OrdinalIgnoreCase))
break;
// Find the student or return null.
Student student = students.FirstOrDefault(s => s.FirstName.Equals(user, StringComparison.OrdinalIgnoreCase));
if (student != null)
{
Console.WriteLine("Student info:");
Console.WriteLine(student);
}
else
{
Console.WriteLine("Student '" + user + "' not found.");
}
Console.WriteLine();
// Wait until a key is pressed.
Console.WriteLine("Press a key to continue..");
Console.ReadKey(true);
} while (true);
}
}
Do something like this:
create a class called Student:
public class Student
{
public string Fname { get; set; }
public string LName { get; set; }
public string Course { get; set; }
public string FinalGrade { get; set; }
}
Then do this
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter you name:");
string name = Console.ReadLine();
Console.WriteLine(gradeDetails(name));
Console.ReadLine();
}
public static string gradeDetails(string name)
{
List<Student> students = new List<Student>()
{
new Student{ Fname = "Scott",LName ="Dee",Course = "Computing", FinalGrade = "66.66m"},
new Student{Fname = "Joe",LName = "Don",Course = "Chemestry", FinalGrade = "80.77m"}
};
var student = students.SingleOrDefault(s => s.LName.ToLower() == name.ToLower());
if (student!=null)
{
return student.Fname + "" + student.LName + "" + student.Course + "" + student.FinalGrade;
}
return string.Empty;
}
}
Ask user to enter name and print name
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace stackoverflow1
{
class Program
{
static void Main(string[] args)
{
string name;
Console.WriteLine("Enter your name : ");
name = Console.ReadLine();
Console.WriteLine("Hello " + name + " , Welcome to OOP!");
Console.ReadKey();
}
}
}
Related
so I have a list of objects in my program that objects in it have (name, last name, id, house, etc.)
I want to create a method called search that lets me find a specific object only with its name. I want to print out the information after search.
(i have one parent class caled wizard and two child classes. one for teachers and one for students(WizardToBe).)
List<WizardTobe> WizardStudents = new List<WizardTobe>();
I received all the information needed below using Readline so all of these are user input.
and all of my codes are in a while loop.
string studentname = Console.ReadLine();
Console.WriteLine("Your last name?");
string studentlast = Console.ReadLine();
Console.WriteLine("And you my child, which house are you from?");
string studentHouse = Console.ReadLine();
Console.WriteLine("And may i know your wizard ID?");
string studentWizID = Console.ReadLine();
Console.WriteLine("And what creature is your lovely Familiar?");
string studentFamiliar = Console.ReadLine();
Console.WriteLine("What is your student ID?");
string babywizID = Console.ReadLine();
Console.WriteLine("sorry this is taking long. Lastly! in School year, what year are you curently in?");
string yearschool = Console.ReadLine();
WizardStudents.Add(new WizardTobe(studentname, studentlast, studentWizID, studentHouse, studentFamiliar, babywizID, yearschool));
I tried to name the object that I want to add to my list as "studentname" which I received with Readline. but I faced another error...
what should I do ? :(
my classes are these:
my parent class
using System;
using System.Collections.Generic;
using System.Text;
namespace HogwartsSignUp
{
public class Wizard
{
string name;
string lastname;
string wizID;
string house;
//teacher
private string yearclass;
private string workID;
//students
private string familiar;
private string studentID;
private string studentyear;
public Wizard(string name, string lastname, string wizID, string house, string familiar, string studentID, string studentyear)
{
this.name = name;
this.lastname = lastname;
this.wizID = wizID;
this.house = house;
this.studentID = studentID;
this.familiar = familiar;
this.studentyear = studentyear;
}
public Wizard(string name, string lastname, string wizID, string house, string yearclass, string workID)
{
this.name = name;
this.lastname = lastname;
this.wizID = wizID;
this.house = house;
this.workID = workID;
this.yearclass = yearclass;
}
public void showStudentInfo()
{
Console.WriteLine("They are a Hogwarts student! Here's the information of them:");
Console.WriteLine("Name: {0} Last name: {1} House: {2} Year: {3} Familiar: {4}", name, lastname,house,studentyear,familiar);
}
public void showTeacherInfo()
{
Console.WriteLine("They are a Hogwarts teacher! Here's the information of them:");
Console.WriteLine("Name:{0} Last Name:{1} House:{2} Teacher of the class: {3}", name, lastname, house, yearclass);
}
}
}
my child class:
using System;
using System.Collections.Generic;
using System.Text;
namespace HogwartsSignUp
{
public class WizardTobe : Wizard
{
string magicwand;
string sportinterest;
string hobby;
public WizardTobe(string name, string lastname, string wizID, string house, string familiar, string studentID, string studentyear) : base (name, lastname, wizID, house, familiar, studentID, studentyear)
{
}
}
}
Use Language Integrated Query to search through the list. Following is the link to the documentation: https://learn.microsoft.com/en-us/dotnet/csharp/linq/
Here is a sample console application using your code that illustrates this.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Console_Example
{
public class WizardTobe
{
public string StudentName { get; set; }
public string StudentLast { get; set; }
public string StudentWizID { get; set; }
public string StudentHouse { get; set; }
public string StudentFamiliar { get; set; }
public string BabyWizID { get; set; }
public string YearsSchool { get; set; }
public WizardTobe(string studentName, string studentLast, string studentWizID, string studentHouse, string studentFamiliar, string babyWizID, string yearsSchool)
{
StudentName = studentName;
StudentLast = studentLast;
StudentWizID = studentWizID;
StudentHouse = studentHouse;
StudentFamiliar = studentFamiliar;
BabyWizID = babyWizID;
YearsSchool = yearsSchool;
}
}
class Program
{
static void Main(string[] args)
{
List<WizardTobe> WizardStudents = new List<WizardTobe>();
string studentname = Console.ReadLine();
Console.WriteLine("Your last name?");
string studentlast = Console.ReadLine();
Console.WriteLine("And you my child, which house are you from?");
string studentHouse = Console.ReadLine();
Console.WriteLine("And may i know your wizard ID?");
string studentWizID = Console.ReadLine();
Console.WriteLine("And what creature is your lovely Familiar?");
string studentFamiliar = Console.ReadLine();
Console.WriteLine("What is your student ID?");
string babywizID = Console.ReadLine();
Console.WriteLine("sorry this is taking long. Lastly! in School year, what year are you curently in?");
string yearschool = Console.ReadLine();
WizardStudents.Add(new WizardTobe(studentname, studentlast, studentWizID, studentHouse, studentFamiliar, babywizID, yearschool));
WizardStudents.Add(new WizardTobe("Peter","","","","","",""));
WizardStudents.Add(new WizardTobe("Steven", "", "", "", "", "", ""));
WizardStudents.Add(new WizardTobe("Maria", "", "", "", "", "", ""));
WizardStudents.Add(new WizardTobe("Ashley", "", "", "", "", "", ""));
string studentToBeSearched = "Ashley";
Console.WriteLine($"\n\nSearching for student named {studentToBeSearched}");
WizardTobe missingStudent = WizardStudents.Where(x => x.StudentName == studentToBeSearched).FirstOrDefault();
Console.WriteLine(missingStudent.StudentName);
Console.WriteLine("Press Any Key");
Console.ReadKey();
}
}
}
Note: Above code is to demonstrate only the solution to the asked problem and not to demonstrate good programming practice.
First of all override ToString() function in your WizardTobe class, return string with all properties you want to print.
public class WizardTobe
{
public string StudentName{ get; set; }
public string StudentLastName{ get; set; }
...
public override string ToString()
{
return $"Student First Name: {StudentName}: Last Name: {StudentLastName}";
}
}
In your program where you want print this information use .Where() or .First() or .Single() as per your requirement.
I am using .Where() as there might be multiple students with same name and lets print all students which satisfy this condition
var results = WizardStudents.Where(s => s.name == somename);
foreach(var result in results)
Console.WriteLine(result);
MSDN :How to override the ToString method
I have an array that is populated with user input and needs to be sorted according to a particular property. I have looked at similar questions on here but it does not seem to help my specific situation and so far nothing I've tried has worked.
The properties for the array are defined in a separate class.
It's a basic program for loading employees onto a system and the output needs to be sorted according to their salary.
*Note that I am a student and I am possibly missing something very basic.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
namespace Instantiating_Objects
{
class Program
{
static void Main(string[] args)
{
//Cleaner cleaner = new Cleaner(); // Instantiantion
// Object Array
Cleaner[] clean = new Cleaner[3]; // Empty Object Array
Cleaner[] loadedCleaners = LoadCleaners(clean);
for (int i = 0; i < loadedCleaners.Length; i++)
{
Console.WriteLine(" ");
Console.WriteLine(loadedCleaners[i].Display() + "\n Salary: R" + loadedCleaners[i].CalcSalary());
}
Console.ReadKey();
}
public static Cleaner[] LoadCleaners(Cleaner[] cleaner)
{
for (int i = 0; i < cleaner.Length; i++)
{
Console.WriteLine("Enter your staff number");
long id = Convert.ToInt64(Console.ReadLine());
Console.WriteLine("Enter your last name");
string lname = Console.ReadLine();
Console.WriteLine("Enter your first name");
string fname = Console.ReadLine();
Console.WriteLine("Enter your contact number");
int contact = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter your number of hours worked");
int hours = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
// Populating object array
cleaner[i] = new Cleaner(id, fname, lname, contact, hours);
}
Array.Sort(, )
return cleaner;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Instantiating_Objects
{
class Cleaner
{
private long staffNo;
private string lastName;
private string fName;
private int contact;
private int noHours;
private double rate = 380.00;
public Cleaner() { }
public Cleaner(long staffId, string name, string surname, int number, int hours)
{
this.contact = number;
this.fName = surname;
this.lastName = name;
this.staffNo = staffId;
this.noHours = hours;
}
public int GetHours() { return noHours;}
public long GetStaffID() { return staffNo; }
public string GetSurname() { return lastName; }
public string GetName() { return fName; }
public int GetNumber() { return contact; }
// Calculate Salary
public double CalcSalary()
{
double salary = 0;
if(GetHours() > 0 && GetHours() <= 50)
{
salary = GetHours() * rate;
}
else if (GetHours() > 50)
{
salary = (GetHours() * rate) + 5000;
}
return salary;
}
public string Display()
{
return "\n Staff no: " + GetStaffID() + "\n Surname" + GetSurname()
+ "\n Name: " + GetName() + "\n Contact no: " + GetNumber();
}
}
}
I will combine Legacy code and Ňɏssa Pøngjǣrdenlarp into one.
First thing as Ňɏssa Pøngjǣrdenlarp said your Cleaner class has no properties.
I removed all your methods and changed it with properties instead
public class Cleaner
{
public Cleaner(long staffId, string name, string surname, int number, int hours)
{
StaffNo = staffId;
FName = name;
LastName = surname;
Contact = number;
NoHours = hours;
}
public long StaffNo { get; set; }
public string LastName { get; set; }
public string FName { get; set; }
public int Contact { get; set; }
public int NoHours { get; set; }
public double Rate => 380.00;
public double Salary
{
get
{
double salary = 0;
if (NoHours > 0 && NoHours <= 50)
{
salary = NoHours * Rate;
}
else if (NoHours > 50)
{
salary = (NoHours * Rate) + 5000;
}
return salary;
}
}
public override string ToString()
{
return "\n Staff no: " + StaffNo + "\n Surname" + LastName
+ "\n Name: " + FName + "\n Contact no: " + Contact;
}
}
Now that we have fixed the class we can look at the Program Main method.
Because we changed the cleaner class to use properties instead we can easily use Linq to orderby
private static void Main(string[] args)
{
//Cleaner cleaner = new Cleaner(); // Instantiantion
// Object Array
var clean = new Cleaner[3]; // Empty Object Array
var loadedCleaners = LoadCleaners(clean).OrderBy(_ => _.Salary).ToArray();
foreach (Cleaner v in loadedCleaners)
{
Console.WriteLine(" ");
Console.WriteLine(v + "\n Salary: R" + v.Salary);
}
Console.ReadKey();
}
You will notice that on this line
var loadedCleaners = LoadCleaners(clean).OrderBy(_ => _.Salary).ToArray();
that i am using Linq to order the Salary.
For more on Linq check out the following docs https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/
On a side note
I would say consistency is key, this will keep your code clean.
Look at the following example, the naming convention is inconsistent
public Cleaner(long staffId, string name, string surname, int number, int hours)
{
StaffNo = staffId;
FName = name;
LastName = surname;
Contact = number;
NoHours = hours;
}
Nice, clean and easy to follow
public Cleaner(long staffId, string firstName, string lastName, int number, int hours)
{
StaffId = staffId;
FirstName = firstName;
LastName = lastName;
Number = number;
Hours = hours;
}
class Program
{
struct St_test
{
public string f_name;
public string l_name;
public int age;
public string email;
}
static void proced(int number)
{
St_test s = new St_test();
Console.WriteLine("Enter the first name :");
s.f_name = Console.ReadLine();
Console.WriteLine("Enter the last name :");
s.l_name = Console.ReadLine();
agee:
Console.WriteLine("Enter the age :");
try { s.age = int.Parse(Console.ReadLine()); }
catch { Console.WriteLine("You enterd viod age"); goto agee; }
Console.WriteLine("Enter the e_mail :");
s.email = Console.ReadLine();
}
static void Main(string[] args)
{
int num;
nume:
Console.WriteLine("enter the count of people you would like to store");
try { num = int.Parse(Console.ReadLine()); }
catch { Console.WriteLine("you enterd void number"); goto nume; }
for (int i = 0; i < num; i++)
{
proced(num);
}
I want to input many of (S) to every number (num) of people.
How to repeat the procedure (proced) and every repeat the (s) variable has new name.
If I write in the procedure (proced) the next :
string r = "s" + number;
how to convert the resulted string (r) to variable to use it instead of (s) variable for each loop
You can't (easily, anyway) access variables by name like that - but there's a much better solution, which is to create a collection of some kind - an array or a list, for example.
I would suggest:
Changing your St_test struct:
Make it a non-nested type
Give it a clearer name (e.g. Person)
Make it a class
Don't expose fields - expose properties
Potentially make it immutable, taking all the values in the constructor
Changing your proced method:
Make it return a new Person
Change the name to follow .NET naming conventions
Stop using goto
Factor out the "request an integer from the user" into a method
Changing your Main method:
Create a List<Person>
Repeatedly call what used to be called proced. but add the return value into the list
You'll end up with code something like this - but don't blindly copy it. Make sure you understand everything that's happening here.
using System;
using System.Collections.Generic;
public sealed class Person
{
public string FirstName { get; }
public string LastName { get; }
public int Age { get; }
public string Email { get; }
public Person(string firstName, string lastName, int age, string email)
{
// TODO: Validation
FirstName = firstName;
LastName = lastName;
Age = age;
Email = email;
}
}
public class Test
{
private static Person CreatePersonFromUserInput()
{
Console.WriteLine("Enter the first name:");
string firstName = Console.ReadLine();
Console.WriteLine("Enter the last name:");
string lastName = Console.ReadLine();
Console.WriteLine("Enter the age:");
int age = RequestInt32();
Console.WriteLine("Enter the email address:");
string email = Console.ReadLine();
return new Person(firstName, lastName, age, email);
}
private static int RequestInt32()
{
string text = Console.ReadLine();
int ret;
while (!int.TryParse(text, out ret))
{
Console.WriteLine("Invalid value. Please try again.");
text = Console.ReadLine();
}
return ret;
}
private static void Main()
{
Console.WriteLine("Enter the count of people you would like to store:");
int count = RequestInt32();
List<Person> people = new List<Person>();
for (int i = 0; i < count; i++)
{
people.Add(CreatePersonFromUserInput());
}
// Just to show them...
foreach (Person person in people)
{
Console.WriteLine(
$"First: {person.FirstName}; Last: {person.LastName}; Age: {person.Age}; Email: {person.Email}");
}
}
}
I'm trying to have a "ToString()-method" return the full name of a customer
Like
//Console.WriteLine("Your name is " + fName + lName);
already does, but in ToString.
class Program
{
static void Main(string[] args)
{
var instance = new Customer();
}
}
--
class Customer
{
public string fName, lName;
public Customer()
{
Console.WriteLine("Please enter your first name");
fName = Console.ReadLine();
Console.WriteLine("Please enter your last name");
lName = Console.ReadLine();
//Console.WriteLine("Your name is " + fName + lName);
}
public override string ToString()
{
return fName + lName;
Console.WriteLine(fName + lName);
}
}
Any feedback om how to solve this would be much appreciated. Tried putting different things in Main but could never get it to compile even.
I will agree that design isnt the best and it is not really clear to me, but I will try and help you with couple of variations
1:
class Customer
{
public string fName, lName;
public Customer()
{
Console.WriteLine("Please enter your first name");
fName = Console.ReadLine();
Console.WriteLine("Please enter your last name");
lName = Console.ReadLine();
Console.WriteLine(ToString());
}
public override string ToString()
{
return fName + lName;
}
}
2:
class Program
{
static void Main(string[] args)
{
var instance = new Customer();
Console.WriteLine(instance.ToString());
}
}
//in Customer class
public override string ToString()
{
return fName + lName;
}
3:
Write printing method in Customer class and call it over ctor like in "1:"
Hopefully I am describing this correctly and clear enough. I am trying to save multiple details entered by a user and save them to list. However the current way I am doing so is only saving the object type/name rather then the data. Below is my code how would I save the objects data rather then the name of the object?
Student stud = new Student();
stud.Enter_Student();
_studentList.Add(stud);
Enter Student
class Student : Person
{
public string StudentId { get; private set; }
public string Subject { get; private set; }
//string[] _studentdb = new string[4];
public Student()
{
StudentId = "abc123";
Subject = "Building Subject";
}
public void Enter_Student()
{
this.Person_Prompt_Print(); //Prompts for user
this.Address_Prompt_Print();
this.Contact_Prompt_Print();
Console.SetCursorPosition(4, 18);
Console.WriteLine("Student ID:");
this.Enter_Person(); // Inputs from user
this.Enter_Address();
this.Enter_Contacts();
StudentId = Console.ReadLine();
Console.SetCursorPosition(30, 18);
}
}
Date sample from person class
class Person
{
Tidyup tidy = new Tidyup();
public string FirstName { get; private set; }
public string Surname { get; private set; }
public string MiddleName { get; private set; }
public string AddressLine1 { get; private set; }
public string AddressLine2 { get; private set; }
public string Town { get; private set; }
public string Postcode { get; private set; }
public string Email { get; private set; }
public string Telephone { get; private set; }
public Person()
{
FirstName = "Name";
Surname = "Surname";
MiddleName = "Middle Name";
AddressLine1 = "Address";
AddressLine2 = "Address Ln2";
Town = "Town";
Postcode = "<xxx>/<xxx>";
Email = "name#buildright.ac.uk";
Telephone = "0800 0000000";
}
public void Person_Prompt_Print()
{
// Program Frame
tidy.Line_Top();
tidy.Line_Base();
tidy.Sides_Left();
tidy.Sides_Right();
Console.SetCursorPosition(4, 2); //Prompts for user
Console.WriteLine("FirstName:");
Console.SetCursorPosition(4, 4);
Console.WriteLine("Surname:");
Console.SetCursorPosition(4, 6);
Console.WriteLine("Middle Name:");
}
public void Address_Prompt_Print()
{
Console.SetCursorPosition(4, 8); //Prompts for user
Console.WriteLine("House Number/Name:");
Console.SetCursorPosition(4, 10);
Console.WriteLine("Street:");
Console.SetCursorPosition(4, 12);
Console.WriteLine("Town:");
Console.SetCursorPosition(4, 14);
Console.WriteLine("Post Code:");
}
public void Contact_Prompt_Print()
{
Console.SetCursorPosition(4, 16);
Console.WriteLine("Email:");
Console.SetCursorPosition(4, 18);
Console.WriteLine("Telephone:");
}
public void Enter_Person()
{
Console.SetCursorPosition(30, 2); // Inputs from user
FirstName = Console.ReadLine();
Console.SetCursorPosition(30, 4);
Surname = Console.ReadLine();
Console.SetCursorPosition(30, 6);
MiddleName = Console.ReadLine();
}
public void Enter_Address()
{
Console.SetCursorPosition(30, 8); // Inputs from user
AddressLine1 = Console.ReadLine();
Console.SetCursorPosition(30, 10);
AddressLine2 = Console.ReadLine();
Console.SetCursorPosition(30, 12);
Town = Console.ReadLine();
Console.SetCursorPosition(30, 14);
Postcode = Console.ReadLine();
}
public void Enter_Contacts()
{
Console.SetCursorPosition(30, 16);
Email = Console.ReadLine();
Console.SetCursorPosition(30, 18);
Telephone = Console.ReadLine();
}
} // End of Class
And finally I am printing out via a simple nested foreach loop
public void Print_all_student()
{
Console.Clear();
foreach (Student t in _studentList)
{
// print another list items.
foreach (Student t1 in _studentList)
{
Console.WriteLine("/" + t + "/" + t1);
}
}
Console.ReadKey();
}
If anyone can help me understand what I am missing and how to access the data to print out I would be grateful. Thank you in advance for any help you can give.
There are lots of issues here, but in your Console.WriteLine call, you are only displaying the Student type, so the ToString method on the Student type will be invoked, which by default will display the type name.
You want to display the individual properties of the Student type, e.g.
foreach (Student student in studentList)
{
Console.WriteLine(student.FirstName);
Console.WriteLine(student.Surname);
// etc
}
Remember that Student derives from Person, so all of the public properties are accessible from a Student reference, because Student is a Person.
Also:
You have a redundant loop - you only need one loop which enumerates the studentList
There is a real mixture of concerns here. Your Student and Person types should not be concerned with UI (i.e. anything to do with Console calls)
Stick with PascalCase (aka UpperCamelCase) for your method names, no underscores