Java - Find specific ID from an array(classes) - java

Having some problems trying to call a method from a class.
Have my main method below
private static boolean findStudentId() {
System.out.println("Please enter your student ID to search for your profile");
int searchId = scanner.nextInt();
//need to be able to find a student's profile from the arraylist by searching their ID
return false;
}
I am trying to call a method from another class and cannot do so. this is my other class I am trying to call
public boolean findStudent(int id) {
for(int i = 0; i< students.size();i++)
{
if (students.equals(id)) {
System.out.println("Found the profile containing information for " + id);
// System.out.println(id.getFirstName()+id.getFirstName()+id.getLastName()+id.getDob());
return true;
} else
System.out.println("Could not find a profile based on the ID you provided");
}
return false;
}
this is my student class that I have created that proclaims the students
public class Student {
private int id;
private String firstName;
private String lastName;
private String dob;
public Student(int id,String firstName, String lastName, String dob) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.dob = dob;
}
public int getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getDob() {
return dob;
}
public static Student createStudentID(int id,String firstName, String lastName, String dob)
{
return new Student(id,firstName, lastName, dob);
}
}

I suggest to add a new class and put all the methods that you are going to be using in that class then in the main class create an object and you could easily use that methods with no problem
+small note the condition in findStudent method should be like
if (students.get(i).id == id)
so it would search for the id in the arraylist

If you want to call a method from another class you can for example create an object of the class you are trying to get the method from. For instance...
If the method you have is located inside of Class A, then create an object of that class.
A classAttribute = new A();
Then to call the method use....
classAttribite.someMethod();

Related

change String in an Arraylist java

I am trying to change a String in an Arraylist but having some trouble being able to access the correct position to change.
So I am tried using students.get(i).getFirstName() = newFirstName; but I was just really just trying different things at this point.
Below is the code I am trying to make changes for firstName and lastName. This is my editStudentId method
public void editStudentID(int findStudentId) {
for (int i = 0; i < students.size(); i++) {
if (students.get(i).getId() != findStudentId) {
continue;
}
System.out.println("Found a profile containing information for " + findStudentId + ":");
System.out.println("What would you like to change in your profile?");
System.out.println("1.First Name");
System.out.println("2.Last Name");
int decision = scanner.nextInt();
switch (decision) {
case 1:
System.out.println("Enter a new first name to continue");
String newFirstName = scanner.next();
//so this is the part when I am currently working on but am having some trouble doing so
students.get(i).getFirstName() = newFirstName;
break;
case 2:
System.out.println("Enter a new last name to continue");
break;
}
return;
}
System.out.println(" Id not found ");
}
Here is my class for Students
public class Student {
private final int id;
private final String firstName;
private final String lastName;
private final String dob;
public Student(int id,String firstName, String lastName, String dob) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.dob = dob;
}
public int getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getDob() {
return dob;
}
public static Student createStudentID(int id,String firstName, String lastName, String dob)
{
return new Student(id,firstName, lastName, dob);
}
}
You should add a set function:
public void setFirstName(String newFirstName) {
firstName = newFirstName;
}
Same for the other variables. Setters and Getters are your friends.
Then call these functions. Use get* to use the variable, not change. Use set to change the variable.
students.get(i).setFirstName(newFirstName);

Got stuck at step 4

Create a Student Class with the following instance variables:
-LastName
-MatNo
-Age
-GPA e.g A+, B-```
Create a Constructor that takes all the instance variables (class fields) as input parameters.
Create Accessor(Getter) and Mutator (Setter) methods for each of the instance variables.
Create a method called calAge that returns the age of a student based on yearofBirth as input parameter.
Create a Tester Program to test the Student class. Do the following:
-Calculate the age of each student object created based on the calAge method.
-Change the GPA of each student by calling the Mutator method of GPA.
-Make sure data about each of the students is printed to the Console.```
My code so far:
package ict;
public class Student {
private String firstName;
private String lastName;
private int mattNo;
private int age;
private String gpa;
public Student(String first, String last, int matt, int ag, String gp)
{
setFirstName(first);
setLastName(last);
setMattNo(matt);
setAge(ag);
setGpa(gp);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getMattNo() {
return mattNo;
}
public void setMattNo(int mattNo) {
this.mattNo = mattNo;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGpa() {
return gpa;
}
public void setGpa(String gpa) {
this.gpa = gpa;
}
}
Create a method called calAge that returns the age of a student based
on yearofBirth as input parameter.
int calAge (int yearofBirth) {
Year y = Year.now();
return y.getValue () - yearOfBirth;
}
now this does not seem to be a very good way, I think you need to consider the month and day that you were born.
also consider to make this method static

Can I pass an object of a superclass in the invoke method while traversing through the methods of subclass via Java Reflection?

So let say I have a Person class which is the super class--> looks something like this:
public class Person {
private String firstName;
private String lastName;
private String adhaarID;
private int employeeID;
public Person(String firstName, String lastName, String adhaarID, int employeeID) {
this.firstName = firstName;
this.lastName = lastName;
this.adhaarID = adhaarID;
this.employeeID = employeeID;
}
public Person() {
}
public String getFullName()
{
return firstName+" "+lastName;
}
public String getFirstName()
{
return firstName;
}
public String getAdhaarID() {
return adhaarID;
}
public String getLastName()
{
return lastName;
}
public int getEmployeeID() {
return employeeID;
}
}
And I have a sub class Employee which extend class Person and have no new method (other than what Class Person already have). In the worst case it gonna have all the methods that class Person have.
In all its method the class Employee calls its super methods:---> looks something like this:
public class Employee extends Person {
public Employee(String firstName, String lastName, String adhaarID, int employeeID) {
super(firstName, lastName, adhaarID, employeeID);
}
public String getFullName() {
return super.getFullName();
}
public String getAdhaarID() {
return super.getAdhaarID();
}
public String getLastName() {
return super.getLastName();
}
public int getEmployeeID() {
return super.getEmployeeID();
}
}
Now I am traversing through all the method of Class Employee through java Reflection.
and I have Class Person object named person.
I am passing that object to invoke the method. Like lets say getAdhaarID of Employee class is invoke on person then the value stored in person object should be returned.
How should I do it. This does not work (see below):
Class<?> clazz = Employee.class;
Method[] arrayOfMethods = clazz.getDeclaredMethods();
for(Method method : arrayOfMethods)
{
String methodReturnValue = method.invoke(person,null).toString();
}
This given an error Person cant be cast to Employee.

Is it possible to return superclass object from initialized subclass without initializing superclass

I have the following code:
public class Person
{
final String firstName;
final String lastName;
final int age;
final UUID identification;
public Person(final String firstName, final String lastName, final int age)
{
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.identification = UUID.randomUUID();
}
protected Person(final String firstName, final String lastName, final int age, final UUID identification)
{
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.identification = identification;
}
/*
Getter functions
*/
public Person asPerson()
{
return this;
}
/*
Hash and Equals code
Equals checks for first/lastName, age, and identification
*/
}
public class Employee extends Person
{
final String occupation;
final float salary;
public Employee(final String firstName, final String lastName, final int age, final String occupation, final float salary)
{
super(firstName, lastName, age);
this.occupation = occupation;
this.salary = salary;
}
public Employee(final Person person, final String occupation, final float salary)
{
super(person.getFirstName(), person.getLastName, person.getAge(), person.getID());
this.occupation = occupation;
this.salary = salary;
}
/*
Getter functions for occupation and salary
*/
#Override
public Person asPerson()
{
return new Person(firstName, lastName, age, identification);
}
/*
Hash and Equals code
Equals checks for equality in occupation and salary
*/
}
public class Volunteer extends Person
{
final String location;
public Volunteer(final String firstName, final String lastName, final int age, final String location)
{
super(firstName, lastName, age);
this.location = location;
}
public Volunteer(final Person person, final String location)
{
super(person.getFirstName(), person.getLastName(), person.getAge(), person.getID());
this.location = location;
}
/*
Getter for location
*/
#Override
public Person asPerson()
{
return new Person(firstName, lastName, age, identification);
}
/*
Hash and Equals
Equals checks for equality in location.
*/
}
public Main
{
public static void main(String[] args)
{
final Person person = new Person("Man", "Fredman", 25);
final Person employee = new Employee(person, "Driver", 65000.0f);
final Person volunteer = new Volunteer(person, "Philly");
final boolean eqality = compareVtoE(volunteer, employee);
System.out.println(equality);
}
private boolean compareVtoE(final Person volunteer, final Person employee)
{
return volunteer.asPerson().equals(employee.asPerson());
}
}
Having an Employee variable already defined, is there a way in the asPerson function in Employee to return the superclass instance without having to call new Person(...)?
My current work-around is using a protected constructor to take in identification, but I would think there is a better way to go about this.
Edit
I have expanded the example. Say I have a Volunteer and an Employee that both extends Person and can take in a Person object in the constructor. They can both be the same person, but do different things. To see if one volunteer is the same as an employee, I need a way to get the Person object, without changing the UUID. My work-around is using a protected constructor in Person that takes in the UUID, used in the subclass constructors with super. I want to avoid using the constructor in asPerson(), creating a new instance of Person.
I am pretty sure there is no way to do what you are asking for as it would require changing the object without changing it, but here are two possible solutions to your comparison problem:
Override the equals method in Person class so you can compare people regardless of their role (employee or volunteer):
#Override
public boolean equals(Object other) {
if (other instanceof Person) {
return identification.equals(((Person)other).identification);
}
return false;
}
If for some reason you can not use equals, for example you need to override it in derived classes with different functionality, just create a isSamePerson function like this:
public boolean isSamePerson(Person other) {
if (other != null) return identification.equals(other.identification);
return false;
}
This will save you unnecessary object duplication, and the danger of loosing track of the people.

JSP Iterate over a user-defined class that inherits

I have two entity classes that represent two tables in my database.
The two tables are User and Student. The Student class(userID, studentID, classID) inherits from the User class(id, firstName, lastName, email).
When I query the database for students, I have a List returned. I then want to use that list to iterate over and display the firstName,lastName,email,and classID for each student. However, it only displays the classID. I believe this is because the object is of a Student that only contains three fields (userID, studentID, classID) and doesn't doesn't contain the names and email. However, because the Student class extends the User class, I thought it should still be able to get the other fields.
Here are my classes
User
public class User {
private int id;
private String firstName;
private String lastName;
private String email;
public User(){
}
public String getFullName(){
return firstName +" "+ lastName;
}
public int getID() {
return id;
}
public void setID(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Student
public class Student extends User {
private int userID;
private int studentID
private int classID
public int getUserID() {
return userID;
}
public void setUserID(int userID) {
this.userID = userID;
}
public int getStudentID() {
return studentID;
}
public void setStudentID(int studentID) {
this.studentID = studentID;
}
public int getClassID() {
return classID;
}
public void setClassID(int classID) {
this.classID = classID;
}
}
JSP
<c:forEach items="${students}" var="student">
<tr>
<td>${student.firstName} ${student.lastName}</td>
<td>${student.email}</td>
<td>${student.classID}</td>
</tr>
</c:forEach>
In my controller class
List<Student> students = getStudents();
output.addObject("students", students);
How can I get it to display, user.firstName, user.lastName, user.email, student.classID
The JSP code seems fine.
If the values are not available in the Student object and should be because of the hierarchy, the problem lies in the code that populates the Student objects after the query is done. You might want to validate how a Student object is created and why the fields which belong to the User object are not set.

Categories