I am trying to display a value from an Array of classes as follows:
class Person
{
private int age;
private string name;
public Person(string Name, int Age)
{
this.name = Name;
this.age = Age;
}
}
class Program
{
static void Main(string[] args)
{
Console.Write("No. of family members: ");
int NoOfEntities = Convert.ToInt32(Console.ReadLine());
Person[] people = new Person[NoOfEntities];
for (int person = 0; person < people.Length; person++)
{
Console.Write($"\nName of No. {person + 1} member: ");
string Name = Console.ReadLine();
Console.Write($"\nAge of No. {person + 1} member: ");
int Age = Convert.ToInt32(Console.ReadLine());
people[person] = new Person(Name, Age);
}
Console.WriteLine(people[0].Age);
}
}
but the compiler complains that 'Person' does not contain a definition for 'Age'. All of the examples I found on internet are using the same method to iterate over the array members. What am I doing wrong?
In your 'Person' class, you have defined age and name as private fields, so they are not accessible from outside of the class (that is why you getting the compiler error). Also note that C# is case sensitive, so age is not the same as Age.
In C# it is common to use public properties for data. It is also common to use names that start with lower case letters for function parameters and local variables. So you probably want your Person class to look like this:
class Person
{
public int Age { get; set; }
public string Name { get; set; }
public Person(string name, int age)
{
this.Name = name;
this.Age = age;
}
}
Related
Im trying to access the Spring splitting method from Person class in Main class, but it doesn't show me only the last result from the text. Its working very good when im integrating System.out.prinln in Person class, in method body but In this homework im not aloud to use System.out in Person class, only in Main class. The result must split the text in "Surname , Name , City". Where am i doing wrong? Thank you!
public class Person {
public String surname;
public String name;
public String city;
public Person(String text) {
String[] person = text.split(" ");
for (int i = 0; i < person.length; i++) {
String surname = person[i].split("[.]")[0];
String name = person[i].split("[./]")[1];
String city = person[i].split("/")[1];
this.surname = surname;
this.name = name;
this.city = city;
}
}
}
public class Main {
public static void main(String[] args) {
Person p1 = new Person("John.Davidson/Berlin Michael.Barton/Rome Ivan.Perkinson/Munich");
System.out.println(p1.surname + p1.name + p1.city);
// the result is the only the last persons info
}
}
I have defined a class like this,
class Person {
final int id,
final String name,
final String email,
final int age,
Person({
this.id,
this.name,
this.email,
this.age});
}
I have a list of Person like,
List<Person> persons;
Now, I need to sort this list as per its constructor parameters like id or age. How can I do that?
You should do that with sort method.
Here's a simple example, sorting the list by the Person name:
class Person {
final int id;
final String name;
final String email;
final int age;
Person({
this.id,
this.name,
this.email,
this.age});
#override
String toString() {
return "Person $name";
}
}
void main () {
List<Person> people = new List();
people
..add(Person(name: "B"))
..add(Person(name: "A"))
..add(Person(name: "D"))
..add(Person(name: "C"));
people.sort((p1, p2) => p1.name.compareTo(p2.name));
print(people);
}
Output:
[Person A, Person B, Person C, Person D]
I recently had an interview,they asked me a small question
the question is follows
There is list of Students
List<Student> students;
Class Student{
String rollNo;
Map<String, Integer> marks ;
}
Stdunt.marks is actually cobination of subject and mark
Should write an method which should return top 10 students array according to the subject.
List<Student> getTop10(String subjectName){
}
The answer i have given is blelow
private static void PrintTop5(ArrayList<Student> list,String subject){
Collections.sort(list, new Comparator<Student>() {
#Override
public int compare(Student st1, Student st2) {
// TODO Auto-generated method stub
return st2.getSubjectMark(subject) - st1.getSubjectMark(subject);
}
});
ArrayList<Student> studentList = new ArrayList<Student>(list.subList(0,5));
for(Student student : studentList){
System.out.println(student.getRollNum() + " MARK : "+student.getSubjectMark(subject));
}
}
Student class look like below
package com.main;
import java.util.HashMap;
public class Student {
private String rollNo;
private HashMap<String, Integer> marks ;
public Student(){
marks = new HashMap<>();
}
public void setRollNumber(String number){
this.rollNo = number;
}
public void setSubjectAndMark(String subName,int mark){
this.marks.put(subName, mark);
}
public HashMap<String, Integer> getAllMarks(){
return marks;
}
public int getSubjectMark(String subject){
return marks.get(subject);
}
public String getRollNum(){
return rollNo;
}
}
In general your idea is correct, to sort the entire list and take top N students, in fact with java 8 it would look cleaner.
private static void PrintTop5(ArrayList<Student> list,String subject){
list.sort(Comparator
.comparing((Student student) -> student.getSubjectMark(subject))
.reversed());
List<Student> studentList = list.stream().limit(5).collect(Collectors.toList());
for(Student student : studentList){
System.out.println(student.getRollNum() + " MARK : "+student.getSubjectMark(subject));
}
}
Consider below example:
public class sample{
private Map myMap;
public Map getMap(){
return myMap;
}
}
In above example, we are returning the map to some other calling class. So my question is how we can say that this class encapsulates/protects its data. The Map that will be returned will be available for modification by other classes.
Thanks,
Rajan
Consider this class Person, which have 2 attributes (name and age).
package app;
/**
*
* #author salathielgenese
*/
public final class Person
{
public Person()
{
setAge(age);
setName(name);
}
public Person(String name, long age)
{
setName(name);
setAge(age);
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public long getAge()
{
return age;
}
public void setAge(long age)
{
this.age = age;
}
private String name;
private long age;
}
Now imagine that some one (let say the calling class) set the age to -19. This will generate inconsistency in your that.
So when you protect your data, your controlling wich kind of action are made possible these data.
You may decide that if the given age is lower than 0 then the age will be set to 0 for example. The code may become...
public void setAge(long age)
{
this.age = age;
if (age < 0)
{
this.age = 0;
}
}
You can do the same with name attribute to prevent setting it to null.
public void setName(String name)
{
this.name = name;
if (name == null || name == "")
{
this.name = "NO NAME";
}
}
We'll say that encapsulation help protecting data.
··························································································
Now let's imagine a class called Carpenter. When you need a table, you just ask it to him. Thus the Carpenter class should provide a method which takes a description of the table you need, and return the build table. Assuming that the method is called buildTable, this method will be declared with public access because it's useful to call it from another Class.
When you ask to the Carpenter to build up your Table, he will need to check some material as well as saw, needle and so on and so far. We (calling class) don't care about this internal mechanism and all methods as well as attributes involved in this process will be declared with private access. i.e to prevents external classes from modifying them, i.e to encapsulate our fields and methods for better protection.
Encapsulating a field let us control access to our data.
Comming back to your code, giving public access to getMap() doesn't prevent calling class to modify its content.
Now look at this Example
Person.java
package app;
/**
*
* #author salathielgenese
*/
public final class Person
{
public Person()
{
setAge(age);
setName(name);
}
public Person(String name, long age)
{
setName(name);
setAge(age);
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
if (name == null || name == "")
{
this.name = "NO NAME";
}
}
public long getAge()
{
return age;
}
public void setAge(long age)
{
this.age = age;
if (age < 0)
{
this.age = 0;
}
}
#Override
public String toString()
{
return "Person{" + "name=" + name + ", age=" + age + '}';
}
private String name;
private long age;
}
Example.java
package app;
/**
*
* #author salathielgenese
*/
public class Example
{
public Example()
{
}
public Example(Person person)
{
this.person = person;
}
public Person getPerson()
{
return person;
}
public void setPerson(Person person)
{
this.person = person;
}
private Person person;
}
**Main class (Loader.java)
package app;
/**
*
* #author salathielgenese
*/
public class Loader
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
// Instantiate an Example with a new created Person
Example example = new Example(new Person("Rajan", 19));
// Retrive person in example and print its description (printing result of implicit call to person.toString() )
Person person = example.getPerson();
System.out.println(person);
// Assigning a new reference to the variable **person** and print its description
person = new Person("Salathiel", 20);
System.out.println(person);
// Print description of Person containning in Example instance
System.out.println(example.getPerson());
}
}
If you look closed this code, you'll understand that you can change attribute of your Map but not the reference to it.
Maybe you can use an unmodifiable map from Java Collection API's :
public class sample{
private Map myMap;
public Map getMap(){
return Collections.unmodifiableMap(myMap));
}
}
I this code
public class Test
{
public string name;
public int age;
public Test (string name, int age)
{
this.name = name;
this.age = age;
}
}
private void button1_Click (object sender, EventArgs e)
{
List <Test> listTest = new List <Test> ();
listTest.Add (new Test ("Pavel", 30));
listTest.Add (new Test ("Dima", 48));
listTest.Add (new Test ("Vova", 48));
dataGridView1.DataSource = listTest;
}
The DataGridView displays three lines, but no value does not tell me that I had incorrectly
Try making the name and age as properties. It will fix your problem.
public class Test
{
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
public Test(string name, int age)
{
this.Name = name;
this.Age = age;
}
}
Hopes you are using .Net 3.5 or more, otherwise Automatic properties doesn't work.
Here is the screenshot