Calling a method from other class, inside other method - java

I couldn't find a solution anywhere, so here it is:
A school project says that to use isEqual(Student) method I must use the hasSameName(Person) inside it.
I have created two classes, Student and Person where boolean hasSameName(Person persons[]) compare the names inside the array and returns true if same name found and false if there's no same person.
public class Person{
private String name,surname,address,email,phoneNumber;
public Person(String name,String surname,String address,String email,String phoneNumber) {
this.name = name;
this.surname = surname;
this.address = address;
this.email = email;
this.phoneNumber = phoneNumber;
}
...
...
...
public boolean hasSameName(Person persons[]) {
boolean flag = false;
for(int i = 0; i<persons.length; i++) {
for (int j = i+1; j< persons.length; j++) {
if((persons[i].getName() == persons[j].getName() && (i!=j))){
flag = true;
}
}
}
if(flag == true)
return true;
else
return false;
}
The project says that boolean isEqual(Student name, Student id) should compare the name and the id values but hasSameName(Person) method must be used.
Here is the Student class:
public class Student extends Person {
private int studentID,semester;
public Student(String name,String surname,String address,String email,String phoneNumber,int studentID,int semester) {
super(name,surname,address,email,phoneNumber);
this.studentID = studentID;
this.semester = semester;
}
.
.
.
.
public boolean isEqual(Student name,Student id) {
//****************i am stuck here. I don't know how to make it work.*******************
}
Any help will be appreciated.

A school project says that to use isEqual(Student) method I must use the hasSameName(Person) inside it.
I assume that hasSameName method should have been implemented like this:
// Person.java
public boolean hasSameName(Person person) {
if (null == person || null == person.getName())
return false;
return person.getName().equals(this.getName());
}
Then, as Student extends Person, you can simply call parent's methods from the child class. So, providing that the signatures of hasSameName and isEqual have been fixed, isEqual may be implemented this way:
// Student.java
public boolean isEqual(Student student) {
return this.hasSameName(student) && this.studentID == student.getStudentID();
}

Related

Pass class variable into method of another class in java

Im just start learning java renow .i created a class student which contain variable ID and name and another class studentlist that is an arraylist of student.
I want to create seach function that allow to pass variale's name of stunt class (ID or name) and the variable value. how can i do it ?
class Student{
String ID;
String name;
public Student(){
}
public Student(String ID,String name){
this.ID = ID;
this.name = name;
}
public String getStudent() {
String info = this.ID +"\t\t\t"+ this.name;
return info;
}
}
class StudentList{
private ArrayList <Student> list = new ArrayList<>();
private int counter = 0;
static Scanner sc = new Scanner(System.in);
public StudentList(){
}
public StudentList(Student stu){
Student student = new Student(stu.ID,stu.name);
this.list.add(student);
this.counter++;
}
public int seach(String type(name or ID) , String value ){
int i;
int found = 0;
for(i = 0; i < list.size();i++){
if(value.equals(list.get(i).type){
found++;
System.out.println(value.equals(list.get(i).type);
}
}
return found;
}
}
Create getter for ID and name in Class Student.
Than you can ask in seach
public int seach(String type , String value ){
int i;
int found = 0;
for(i = 0; i < list.size();i++){
Student student = list.get(i);
if(value.equals(student.getID()) || value.equals(student.getName())){
found++;
System.out.println(value.equals(list.get(i).type);
}
}
return found;
}
First I recommend to set the attributes of your Student class to private. Then you could add setters and getters.
public class Student {
private String ID;
private String name;
public Student() {}
public Student(String ID, String name) {
this.ID = ID;
this.name = name;
}
public String getID() { return ID; }
public String getName() { return name;
public void setID(String ID) { this.ID = ID; }
public void setName(String name) { this.name = name; }
}
In your class StudentList I would split and extend the functionalities of the search instead of passing the value type as an additional argument.
public class StudentList {
...
public int searchByName(String name) {
for(int i=0; i < list.size(); i++) {
if(list.get(i).getName().equals(name)) return i;
}
return -1;
}
public int searchByID(String ID) {
for(int i=0; i < list.size(); i++) {
if(list.get(i).getID().equals(ID)) return i;
}
return -1;
}
public int searchStudent(Student stud) { return list.indexOf(stud); }
}
If you really need a function that bundles all of that you could add another function that decides by a flag which function should be called with the passed argument. You could also add a check for arguments here while having more flexibility and separation of responsibilities.
public int search(int flag, arg Object) {
if(flag == 0) return searchStudent((Student) arg);
else if(flag == 1) return searchByID((String) arg);
else return searchByName((String) arg);
}
Additional side note: if you want to indicate the current number of students in the list with your counter variable, I highly recommend to remove this variable and always call the size() method of your list when needed. Every Java collection (i.e. ArrayList) provides it and it will always return the correct value after removing or adding students. Implementing your own counter for this task will result in a more error prone source code.

Unit testing: Prevent creation of duplicate objects

My professor gave us this homework exercise and has created a project with
a bunch of unit tests.
Our goal is to make sure we can pass those unit tests.
We have three classes.
A class called Person with a name and an age,
a class Speaker that extends Person,
and a class Attendee that also extends Person.
I am struggling with making sure that there are no duplicate people. generateRandomString() was implemented by the professor and just returns a random string.
I already created the class,
it's constructor,
getters,
and setters.
I also overrode the method equals() in the class Person
This is the test our professor gave us:
#Test
public void testNoDuplicatePerson() {
HashSet<Person> people = new HashSet<Person>();
String name = generateRandomString();
Person p = new Speaker(name);
people.add(p);
assertEquals(1,people.size());
p = new Attendee(name);
people.add(p);
assertEquals(1,people.size());
}
How can I pass this test?
EDIT: I decided to post the code of the three classes:
Person
```java
public abstract class Person {
private String name;
private int age;
public Person(String name) {
this.name = name;
this.age = 0;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean equals(Object o) {
if (o == null || !(o instanceof Person))
return false;
Person converted = (Person) o;
if (this.getName().equals(converted.getName()) && this.getAge() == converted.getAge())
return true;
return false;
}
}
Speaker:
public class Speaker extends Person {
private int fee;
public Speaker(String name) {
super(name);
this.fee = 0;
}
public Speaker(String name, int age) {
super(name, age);
this.fee = 0;
}
public Speaker(String name, int age, int fee) {
super(name, age);
this.fee = fee;
}
public int getFee() {
return fee;
}
public void setFee(int fee) {
this.fee = fee;
}
public String toString() {
return "Speaker " + this.getName() + " as a fee value of " + this.getFee() + ".";
}
}
Attendee:
public class Attendee extends Person {
private boolean paid;
public Attendee(String name) {
super(name);
this.paid=false;
}
public Attendee(String name, int age) {
super(name, age);
this.paid=false;
}
public boolean hasPaid(){
if (this.paid==true)
return true;
return false;
}
public String toString(){
return "Attendee "+this.getName()+(this.hasPaid() ? " has":" hasn't")+" paid its registration.";
}
}
As mentioned by #JB Nizet, when you override the equals method of a class,
you must override the hashCode method.
Note the name of the class in the jUnit test: HashSet.
That depends on the hashCode method.
Solution:
a. Learn to read the java API docs.
Here is a link to the v8 JavaDocs.
Read the HashSet page.
b. Implement the hashCode method.
You clearly have Internet access,
so, if you don't know how to implement a hashCode method,
try a google search for "how do I implement a Java hashCode method".
Hint: String already implements a hashCode method.

Calling an object arraylist from another class and iteration through it

I have a problem accessing the arraylist I created in a class. I tried going through the answers of questions similar to mine but unfortunately I was unable to solve the problem.
So I have two classes Student and Person and I want to iterate through the arraylist of Person in the class Student. (The code doesn't really make sense, I know. I just want to understand).
I tried two approaches :
1) creating a variable of type Person in Student class and calling the get method from person class.
2) creating a get method in the class person that returns arraylist.
Both are not working properly when i tried to call the isHere method in the main method.(false was printed instead of true)
I think my two approaches intialise a new array of type Person and not call the arraylist to which elements are already added. How can solve this?
import java.util.ArrayList;
public class Student {
private Person p;
private String name;
private int age;
private String address;
public Student() {
}
public Student(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
public boolean isHere(String name) {
p = new Person();
// I also tried for(Person per : p.getList)
for (Person per : this.getL()) {
if (per.getName().equals(name)) {
System.out.println("hi");
return true;
}
}
return false;
}
public ArrayList<Person> getL() {
return p.getList();
}
public Person getP() {
return p;
}
public void setP(Person p) {
this.p = p;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
The Person class:
import java.util.ArrayList;
public class Person {
private String name;
private ArrayList<Person> list = new ArrayList<Person>();
Person() {
}
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList<Person> getList() {
return list;
}
public void setList(ArrayList<Person> list) {
this.list = list;
}
public void add(String name) {
list.add(new Person(name));
}
}
The statement p = new Person() in your isHere(..) method is creating a new Person object. When that Person object is created, the name in object p will be null and the list will be empty. So the for loop is never executed as the list is empty and hence it returns false.
If you ever want your code to run, you should not create the Person object and then immediately iterate through it because it will have nothing. You have to either add something to it or use a Person object which you believe will be populated before you run the isHere(..) method

Creating or Instiatiating an ArrayList of Objects for Each User

Alright so, I am building an online registration system for a university. It's a fairly basic system written in java so there's no database issue to worry about. My problem is this: I have a class of objects called Course. Each course has a list of attribute (id, time, instructor, etc.). Each user then, has an arraylist (or schedule if you will) of Course objects which they can add or remove. My question is how do I create an arraylist for each student/user? Would it be beneficial to have a separate arraylist of Courses like a catalog from which to choose from? Any advice on the subject would be of help. If you'd like to see an example of my code thus far let me know and I'll edit my post to include it.
public class Course {
private int courseId;
private String courseDes;
private String courseIns;
private int time;
public Course(int courseId, String courseDes, String courseIns, int time) {
courseId = this.courseId;
courseDes = this.courseDes;
courseIns = this.courseIns;
time = this.time;
}
No need to use maps; you've expressed the right relationship yourself: "Each user has an ArrayList". The way to express a has-a relationship is with instance fields:
public class Student {
private final List<Course> courses = new ArrayList<>();
//write methods that operate on courses, or make courses public
....
Representing courses as a Course object is simplest if you care about the properties of the courses in any way. If however you only need the know the course ID, or if you need to be storing a large amount of Students, you can save space by storing courses as integers or shorts and looking them up in a static table.
I would have three separate classes Courses, Student and Enrollment.
public class Course {
private int courseId;
private String courseDes;
private String courseIns;
private int time;
public Course(int courseId, String courseDes, String courseIns, int time) {
courseId = this.courseId;
courseDes = this.courseDes;
courseIns = this.courseIns;
time = this.time;
}
}
Student
public class Student {
private final int studentID;
private final String name;
private Set<Course> studentCourses;
public Student(int studentId, String name) {
this.name = name;
this.studentID = studentId;
}
public String getName(){
return this.name;
}
public int getStudentId(){
return this.studentID;
}
void addCourse(Course course) {
if(!studentCourses.contains(course)){
studentCourses.add(course);
}
else{
studentCourses.remove(course);
studentCourses.add(course);
}
}
#Override
public int hashCode() {
int hash = 7;
hash = 23 * hash + this.studentID;
hash = 23 * hash + (this.name != null ? this.name.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Student other = (Student) obj;
if (this.studentID != other.studentID) {
return false;
}
if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
return false;
}
return true;
}
}
Enrollment
class Enrollment{
//This Map will group student with the same name
private Map<String, List<Student>> enrollment;
public Enrollment(Student student){
if(enrollment.containsKey(student.getName())){
enrollment.get(student.getName()).add(student);
}else
{
List<Student> newStudent = new ArrayList<Student>();
newStudent.add(student);
enrollment.put(student.getName(), newStudent);
}
}
public void addCourse(Student student, Course course){
try{
List<Student> studentSameName = enrollment.get(student.name);
for(Student studentEntry : studentSameName){
if(studentEntry.getStudentId() == student.getStudentId()){
studentEntry.addCourse(course);
}
}
}catch(NullPointerException e){
//student does not exist
//TODO Add Logic
}
}
public void removeStudent(Student student){
//TODO Add Logic
}
}

What is Getters, setters, equals and toString for this program. How to write it

public class People {
// Code to create a random set of people omitted
public Set getAllPeople() {
return people;
}
public void setPerson(Person person) {
if (person.getId() == -1) {
person.setId(getNextId());
}
people.remove(person);
people.add(person);
}
public void deletePerson(Person person) {
people.remove(person);
}
private Set people = new HashSet();
}
public class Person
{
private int id;
private String name;
private String address;
private float salary;
// Getters, setters, equals and toString omitted
}
While looking after the DWR website i found this example.It states that they omitted Getters, setters, equals and toString. How to write those for this program. I wish to run this program and see. Any Suggestions Please. Help out..
Getters and Setters are used to retrieve your "private" variables ( = variables visible inside the class they are defined only), from outside the class.
For instance:
private String name;
would have a getter like this:
public String getName() {
return name;
}
And a setter like this:
public void setName(String name) {
this.name = name;
}
(you could use "protected" if you only wanted this variable to be visible in the package, and not in the whole project).
the toString() method is here if you want to display some information about your object, which might be useful from a debugging point of view.
The equals method would be used to know how you want to compare to objects of Person type (by ids only for instance).
Have a look at this link to have more info on what is equals.
As RonK suggested, be sure to implement hashCode if you do implement equals, they go together, and have to use the same fields (part of the contract).
The rule is that if:
objectA.equals(objectB) returns true
then
objectA.hashCode() has to be equal to objectB.hashCode()
for each property in Person class you need to define 2 methods
for example id:
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
and you need to override equals and hashcode method to put your own condition for equality
public boolean equals(Object that) {
if (that == null) {
return false;
}
if (!(that instanceof Person)) {
return false;
}
return this.id == ((Person) that).id;
}
public int hashCode() {
return id * 17;
}
public class Person
{
//Id should be unique
private int id;
private String name;
private String address;
private float salary;
public Person(int id, String name, String address, float salary)
{
this.id = id;
this.name = name; //Maybe check for null
this.address = address; //Maybe check for null
this.salary = salary; //Maybe check for > 0
}
public int getId()
{
return id;
}
//No setID() - do you want that? you properly shouldn't
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address; //Maybe check for null
}
public float getSalary()
{
return salary;
}
public setSalary(float salary)
{
this.salary = salary;
}
//A person is equal if they have the same ID
#Override
public boolean equals(Object obj)
{
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Person person = (Person)obj;
return person.id == id;
}
#Override
public int hashCode()
{
return id;
}
//Just returns the name but you could return more details
#Override
public String toString()
{
return name;
}
}
Added hashCode which is essential - especially if you use it in a HashSet.

Categories

Resources