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}");
}
}
}
Related
namespace HW
{
class Program
{
struct Employee
{
int join_year;
int age;
string dept;
public void getval(int join_year, int age, string dept)
{
this.join_year = join_year;
this.age = age;
this.dept = dept;
}
public void showval()
{
Console.WriteLine("Joining year of Employee is: {0}", this.join_year);
Console.WriteLine("Age of Employee is: {0}", this.age);
Console.WriteLine("Department of Employee is: {0}", this.dept);
}
}
static void Main(string[] args)
{
Employee emp = new Employee();
Console.Write("Enter Joining Year: ");
int join_year = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Age: ");
int age = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Department: ");
string dept = Console.ReadLine();
emp.getval(join_year, age, dept);
emp.showval();
}
}
}
So yeah basically over here I'm adding the values and they are getting printed too. Now I just want to take these records add it into a list or array so that I can access the records by choice.
if I understand it right, you want to do this.
List<string>() list = new List<string>();
for(int i = 0; i < 3; i++)
{
switch(i)
{
case 0: list.Add(join_year.ToString());
break;
case 1: list.Add(age.ToString());
break;
case 2: list.Add(dept);
break;
}
}
it is pretty simplistic, but will do the job.
I have been searching about creating a new object within a loop, found some answers and topics but its way too hard to understand. Making it with lists and arrays etc.
What I am trying to do is, get an input from the user(lets say 3), and create objects as many as the user will with the unique names. Like newperson1, newperson2, newperson3 etc.
My code looks like this:
class person
{
}
class Program
{
static void Main(string[] args)
{
Console.Write("How many persons you want to add?: ");
int p = int.Parse(Console.ReadLine());
for (int i = 0; i < p; i++)
{
person newperson = new person();
}
}
}
Is there any way to create new objects with following numbers in the end of the object name?
Thanks!
Edit:
My new code looks like this; I was more thinking like this:
class Persons
{
//Person object id
public int id { get; set; }
//Persons name
public string name { get; set; }
//Persons adress
public string adress { get; set; }
//Persons age
public int age { get; set; }
}
class Program
{
static void Main(string[] args)
{
Console.Write("How many persons you want to add?: ");
int count = int.Parse(Console.ReadLine());
var newPersons = new List<Persons>(count);
for (int i = 0; i < count; i++)
{
newPersons[i].id = i;
Console.Write("Write name for person " + i);
newPersons[i].name = Console.ReadLine();
Console.Write("Write age for person " + i);
newPersons[i].age = int.Parse(Console.ReadLine());
Console.Write("Write adress for person " + i );
newPersons[i].adress = Console.ReadLine();
}
Console.WriteLine("\nPersons \tName \tAge \tAdress");
for (int i = 0; i < count; i++)
{
Console.WriteLine("\t" + newPersons[i].name + "\t" + newPersons[i].age + "\t" + newPersons[i].adress);
}
Console.ReadKey();
}
}
I understand that I have to create object with arrays or lists. But I didn't really understand how I will access them after they are created person by person..
It's fairly advanced to create dynamic classes (where the actual name of the object is different). In other words, it's WAY harder to do what you're asking than to create a List or an Array. If you spend an hour or two studying Collections, it will pay off in the long run.
Also, you might consider adding a Name property to your Person class, and then you can set that differently for each person you create.
As others have said, you will need to store them in an array or list:
public class Person
{
public string Name { get; set; }
}
static void Main(string[] args)
{
Console.Write("How many persons you want to add?: ");
int p = int.Parse(Console.ReadLine());
var people = new List<Person>();
for (int i = 0; i < p; i++)
{
// Here you can give each person a custom name based on a number
people.Add(new Person { Name = "Person #" + (i + 1) });
}
}
Here's an example of one way to access a Person from the list and let the user update the information. Note that I've added a few properties to the Person class:
public class Person
{
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
public string Address { get; set; }
public int Age
{
// Calculate the person's age based on the current date and their birthday
get
{
int years = DateTime.Today.Year - DateOfBirth.Year;
// If they haven't had the birthday yet, subtract one
if (DateTime.Today.Month < DateOfBirth.Month ||
(DateTime.Today.Month == DateOfBirth.Month &&
DateTime.Today.Day < DateOfBirth.Day))
{
years--;
}
return years;
}
}
}
private static void GenericTester()
{
Console.Write("How many persons you want to add?: ");
string input = Console.ReadLine();
int numPeople = 0;
// Make sure the user enters an integer by using TryParse
while (!int.TryParse(input, out numPeople))
{
Console.Write("Invalid number. How many people do you want to add: ");
input = Console.ReadLine();
}
var people = new List<Person>();
for (int i = 0; i < numPeople; i++)
{
// Here you can give each person a custom name based on a number
people.Add(new Person { Name = "Person" + (i + 1) });
}
Console.WriteLine("Great! We've created {0} people. Their temporary names are:",
numPeople);
people.ForEach(person => Console.WriteLine(person.Name));
Console.WriteLine("Enter the name of the person you want to edit: ");
input = Console.ReadLine();
// Get the name of a person to edit from the user
while (!people.Any(person => person.Name.Equals(input,
StringComparison.OrdinalIgnoreCase)))
{
Console.Write("Sorry, that person doesn't exist. Please try again: ");
input = Console.ReadLine();
}
// Grab a reference to the person the user asked for
Person selectedPerson = people.First(person => person.Name.Equals(input,
StringComparison.OrdinalIgnoreCase));
// Ask for updated information:
Console.Write("Enter a new name (or press enter to keep the default): ");
input = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(input))
{
selectedPerson.Name = input;
}
Console.Write("Enter {0}'s birthday (or press enter to keep the default) " +
"(mm//dd//yy): ", selectedPerson.Name);
input = Console.ReadLine();
DateTime newBirthday = selectedPerson.DateOfBirth;
if (!string.IsNullOrWhiteSpace(input))
{
// Make sure they enter a valid date
while (!DateTime.TryParse(input, out newBirthday) &&
DateTime.Today.Subtract(newBirthday).TotalDays >= 0)
{
Console.Write("You must enter a valid, non-future date. Try again: ");
input = Console.ReadLine();
}
}
selectedPerson.DateOfBirth = newBirthday;
Console.Write("Enter {0}'s address (or press enter to keep the default): ",
selectedPerson.Name);
input = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(input))
{
selectedPerson.Address = input;
}
Console.WriteLine("Thank you! Here is the updated information:");
Console.WriteLine(" - Name ............ {0}", selectedPerson.Name);
Console.WriteLine(" - Address ......... {0}", selectedPerson.Address);
Console.WriteLine(" - Date of Birth ... {0}", selectedPerson.DateOfBirth);
Console.WriteLine(" - Age ............. {0}", selectedPerson.Age);
}
The closest thing to doing what you are asking is to create a dictionary:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var dictionary = new Dictionary<string, Person>();
Console.Write("How many persons you want to add?: ");
int p = int.Parse(Console.ReadLine());
for (int i = 0; i < p; i++)
{
dictionary.Add("NewPerson" + i, new Person());
}
// You can access them like this:
dictionary["NewPerson1"].Name = "Tim Jones";
dictionary["NewPerson2"].Name = "Joe Smith";
}
public class Person
{
public string Name {
get;
set;
}
}
}
You can create dynamically named variables in C#.
What you need is a collection of persons:
var persons = new List<person>();
for (int i = 0; i < p; i++)
{
persons.Add(new person());
}
Arrays and List are basic building blocks. they should't be very hard. but if you don't want to deal with them try creating a method whose responsibility is to give you your new objects given count.
static void Main(string[] args)
{
Console.Write("How many persons you want to add?: ");
int p = int.Parse(Console.ReadLine());
var newPersons = CreatePersons(p);
foreach (var person in newPersons)
{
Console.WriteLine("Eneter age for Person :" person.Name);
person.Age = Console.ReadLine();
}
}
static IEnumerable<Person> CreatePersons(int count)
{
for (int i = 0; i < count; i++)
{
yield return new Person{ Name="newPerson" +1 };
}
}
Try this one.
I am creating Person (Object) as array first (like creating object array)
Then I am assigning that to the Person Class.
class Persons
{
//Person object id
public int id { get; set; }
//Persons name
public string name { get; set; }
//Persons adress
public string adress { get; set; }
//Persons age
public int age { get; set; }
}
class Program
{
static void Main(string[] args)
{
Console.Write("How many persons you want to add?: ");
int count = int.Parse(Console.ReadLine());
//var newPersons = new List<Persons>(count);
Persons[] newPersons = new Persons[count];
for (int i = 0; i < count; i++)
{
newPersons[i] = new Persons();
newPersons[i].id = i+1;
Console.Write("Write name for person " + (i+1) + "\t");
newPersons[i].name = Console.ReadLine();
Console.Write("Write age for person " + (i + 1) + "\t");
newPersons[i].age = int.Parse(Console.ReadLine());
Console.Write("Write adress for person " + (i + 1) + "\t");
newPersons[i].adress = Console.ReadLine();
}
Console.WriteLine("\nPersons Name \tAge \tAdresss \n");
for (int i = 0; i < count; i++)
{
Console.WriteLine(newPersons[i].name + "\t\t" + newPersons[i].age + "\t" + newPersons[i].adress);
}
Console.ReadKey();
}
}
If you want to iterate through an array of object in C#, you need to define the ToString() method (override) and after that, you can use the ToString() method.
I have an assignment in my intro class where I need to prompt the user for first name, last name, birth year, and the current year. The program needs to output the information back to the user along with calculated age, maximum heartrate (220 - age), and target heartrate range (50% to 85%). My class should have a constructor that receives the inputted data as parameters. Each attribute should have get/sets and there should be properties to calculate age, max heart rate, and the target range. This is what I have so far. I think I have done what it asks but I'm not sure what args to use when calling the constructor. Or maybe I am misunderstanding a concept here.
Thanks in advance for any advice.
using System;
namespace Assignment2
{
public class HeartRates
{
private string firstname;
private string lastname;
private int birthyear;
private int currentyear;
private int age;
private double maxrate;
private double mintarget;
private double maxtarget;
public string Firstname
{
get { return firstname; }
set { firstname = value; }
}
public string Lastname
{
get { return lastname; }
set { lastname = value; }
}
public int Birthyear
{
get { return birthyear; }
set { birthyear = value; }
}
public int Currentyear
{
get { return currentyear; }
set { currentyear = value; }
}
public int Age
{
get { return currentyear - birthyear; }
set { age = currentyear - birthyear; }
}
public double MaxRate
{
get { return 220 - Age; }
set { maxrate = value; }
}
public double MinTarget
{
get { return MaxRate * .5; }
set { mintarget = value; }
}
public double MaxTarget
{
get { return MaxRate * .85; }
set { maxtarget = maxrate * .85; }
}
public HeartRates(string firstname, string lastname, int birthyear, int currentyear)
{
Console.WriteLine("Please enter your first name:");
this.firstname = Console.ReadLine();
Console.WriteLine("Please enter your last name:");
this.lastname = Console.ReadLine();
Console.WriteLine("Please enter your birth year:");
this.birthyear = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the current year:");
this.currentyear = Convert.ToInt32(Console.ReadLine());
}
}
public class Program
{
public static void Main()
{
HeartRates newheartrates = new HeartRates();
Console.WriteLine("Your name is {0} {1}, you were born in {2}, the current year is {3}", newheartrates.Firstname, newheartrates.Lastname, newheartrates.Birthyear, newheartrates.Currentyear);
Console.WriteLine("Your age is {0}", newheartrates.Age);
Console.WriteLine("Your maximum heart rate is {0}", newheartrates.MaxRate);
Console.WriteLine("Your target heart rate range is from {0} to {1}.", newheartrates.MinTarget, newheartrates.MaxTarget);
}
}
}
You are on the right track, but I think you are little confused.
You should move this part
Console.WriteLine("Please enter your first name:");
this.firstname = Console.ReadLine();
Console.WriteLine("Please enter your last name:");
this.lastname = Console.ReadLine();
Console.WriteLine("Please enter your birth year:");
this.birthyear = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the current year:");
this.currentyear = Convert.ToInt32(Console.ReadLine());
To your main function.
Then use the constructor you created instead.
HeartRates newheartrates = new HeartRates(firstname, lastname, birthyear, currentyear);
What you have could kind of work, but 1) you are not calling the constructor you created, you are calling a constructor with no parameter. Typically would don't want user input in your object constructors. It makes more sense to do it in the main function and keep your input/output together.
Hope this helps, welcome to Stackoverflow.
First get user inputs (inside of your main method,not in the constructor):
Console.WriteLine("Please enter your first name:");
string firstname = Console.ReadLine();
Console.WriteLine("Please enter your last name:");
string lastname = Console.ReadLine();
Console.WriteLine("Please enter your birth year:");
int birthyear = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the current year:");
int = currentyear = Convert.ToInt32(Console.ReadLine());
Then call your constructor:
HeartRates newheartrates = new HeartRates(firstname,lastname,birthyear,currentyear);
And change your constructor:
public HeartRates(string firstname, string lastname, int birthyear, int currentyear)
{
this.firstname = firstname;
this.lastname = lastname;
this.birthyear = birthyear;
this.currentyear = currentyear;
}
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();
}
}
}
I'm trying to figure out how to populate an array with an object with multiple variables. What I need is to create an array, not a list(I'm trying to learn arrays), and populate it with 5 different bourbons. Is it possible to populate the array and store the name, age, distillery in just one index? For example,
If I called index 0, it would display:
Name: Black Maple Hill
Distillery: CVI Brands, Inc
Age: 8 years
I have this so far, in which bourbon is a derived class from whiskey and call a method in the main class to prompt user for entry.
class Bourbon : Whiskey
{
private Bourbon[] bBottles = new Bourbon[5];
public void bourbon(string name, string distillery, int age)
{
Name = name;
Distillery = distillery;
Age = age;
}
public void PopulateBottles()
{
Console.WriteLine("Please enter the information for 5 bourbons:");
for (int runs = 0; runs < 5; runs ++)
{
}
}
}
In your code you haven't defined the value variable that you are using inside the for loop. You could create new instances of the class and then store them inside the array:
public void PopulateBottles()
{
Console.WriteLine("Please enter the information for 5 bourbons:");
for (int runs = 0; runs < 5; runs ++)
{
Console.WriteLine("Name:");
var name = Console.ReadLine();
Console.WriteLine("Distillery:");
var distillery = Console.ReadLine();
Console.WriteLine("Age:");
var age = int.Parse(Console.ReadLine());
var bourbon = new Bourbon(name, distillery, age);
bBottles[runs] = bourbon;
}
}
Also make sure you have defined the Bourbon class constructor properly:
public Bourbon(string name, string distillery, int age)
{
Name = name;
Distillery = distillery;
Age = age;
}
#Jonathan. Yes, it is possible, based on my interpretation. You can try making use of indexers.
Class Bourbon : Whiskey {
public Bourbon this[int index]
{
get {
return bBottles[index];
}
set {
bBottles[index] = value;
}
}
}
Check this Need to Create Property and One Constructor to achieve your requirement.
class Bourbon
{
private Bourbon[] bBottles = new Bourbon[5];
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string distillery;
public string Distillery
{
get { return distillery; }
set { distillery = value; }
}
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
public Bourbon(string name, string distillery, int age)
{
Name = name;
Distillery = distillery;
Age = age;
}
public void PopulateBottles()
{
Console.WriteLine("Please enter the information for 5 bourbons:");
for (int runs = 0; runs < 5; runs++)
{
Console.WriteLine("Name:");
var name = Console.ReadLine();
Console.WriteLine("Distillery:");
var distillery = Console.ReadLine();
Console.WriteLine("Age:");
var age = int.Parse(Console.ReadLine());
var bourbon = new Bourbon(name, distillery, age);
bBottles[runs] = bourbon;
}
}
}