Could anyone help me fix the below-attached code? I've written a Java method that hires a person by surname, and what I mean by that is that the value passed in the method should be the last name of an object reference (an object of a class Employee which we desire to hire in the company).
However, the program is complaining that the surname cannot be resolved to a type. Now, getSurname() is a method of a private instance variable defined in Employee which is an abstract class (and a superclass for two subclasses Worker and Officer, but that's irrelevant to the problem). Anyone willing to give me a hand?
public class CompanyArrayList {
private ArrayList<Employee> arrayList;
public CompanyArrayList(int employeeNumber) {
ArrayList<Employee> arrayList = new ArrayList<Employee>(employeeNumber);
}
public String hire(Employee employee.getSurname()) { // the object of this class will be generated in the "main" method.
for (int i = 0; i < employeeNumber; i++) {
if (!arrayList.contains(employee.getSurname())) {
arrayList.add(employee);
return "Hired"; // "return" terminates the execution of the method.
}
} // WHY?
}
public String fire(Employee employee) {
for (Employee i : arrayList) {
if (employee.getSurname().equals(i.getSurname())) {
arrayList.remove(employee);
return "Fired"; // returns nothing and terminates the method execution.
}
}
return "The person of the" + employee.getSurname() + " surname doesn't work in the company";
}
}
public abstract class Employee {
private String surname;
private float contract; // contract = workperiod
public String getSurname() { // Here we're asking about a surname of an employee
return surname;
}
public float getContract() {
return contract;
}
public Employee(String surname, float contract) {
this.surname = surname;
this.contract = contract;
}
public abstract float pay();
public abstract String group();
}
Change String hire(Employee employee.getSurname()) to String hire(Employee employee).
Edit:
About the Employee that you want to hire() by surname (which I've explained you why this is a bad idea) do this:
public String hire(Employee employee) {
for (int i = 0; i < arrayList.size(); i++) { // you had employeeNumber instead of arraylist.size() but hire() method does not know anything about that variable
Employee temp = arraylist.get(i);
if (temp.getSurname().equals(employee.getSurname)) {
arrayList.add(employee);
return "Hired"; // "return" terminates the execution of the method.
}
}
}
Related
I have a program I am working with to help me practice my coding skills. The program has the following scenario: there is a classroom of 20 students, where the record is taken of the students' names, surnames, and age. Half of these students take part in the school's athletics. Here, record is kept of their races that they have done and the ones they've won.
In this program, I have three classes:
runStudents - class with main method
Students (String name, String surname, int age) - parental class
AthleticStudents (String name, String surname, int age, int races, int victories) - sub class
The user should be able to add another race (and win) to the object. As seen by the code provided, an Array is created to store the 20 Students objects. I have to be able to access a method to alter the object in the array, but this method is not in the parental class (the class the objects are created from.
public class Students
{
private String name;
private String surname;
private int age;
public Students()
{
}
public Students(String name, String surname, int age)
{
this.name = name;
this.surname = surname;
this.age = age;
}
public String getName()
{
return this.name;
}
public String getSurname()
{
return this.surname;
}
public double getAge()
{
return this.age;
}
public void setName(String name)
{
this.name = name;
}
public void setSurname(String surname)
{
this.surname = surname;
}
public void setAge(int age)
{
this.age = age;
}
public String toString()
{
return String.format("name\t\t: %s\nsurname\t\t: %s\nage\t\t: %s",
this.name, this.surname, this.age);
}
}
public class AthleticStudents extends Students
{
private int races;
private int victories;
public AthleticStudents()
{
}
public AthleticStudents(String name, String surname, int age, int
races, int victories)
{
super(name, surname, age);
this.races = races;
this.victories = victories;
}
public int getRaces()
{
return this.races;
}
public int getVictories()
{
return this.victories;
}
public void setRaces(int races)
{
this.races = races;
}
public void setVictories(int victories)
{
this.victories = victories;
}
public void anotherRace()
{
this.races = this.races + 1;
}
public void anotherWin()
{
this.victories = this.victories + 1;
}
public String toString()
{
return super.toString() + String.format("\nnumber of races\t:
%s\nnumber of wins\t: %s", this.races, this.victories);
}
}
public class runStudents
{
public static void main(String[]args)
{
Students[] myStudents = new Students[20];
myStudents[0] = new Students("John", "Richards", 15);
myStudents[1] = new AthleticStudents("Eva", "Grey", 14, 3, 1);
myStudents[2] = new Students("Lena", "Brie", 15);
for (int i = 0; i < 3; i++)
System.out.println(myStudents[i].toString() + "\n\n");
}
}
I want to be able to do the following:
AthleticStudents[1].anotherRace();
but cannot do so as the array object is derived from the parental class, and I declared the method in the sub class. How can I link the two?
I assume that you create an array of the parent class instances. Just cast the instance this way (you better check whether the element is the instance of a subclass):
if (AthleticStudents[1] instanceof AthleticStudents)
((AthleticStudents) AthleticStudents[1]).anotherRace();
I'm not sure if this is exactly what you're looking for but it worked well for me. Instead of trying to access AthleticStudents method anotherRace() like that, try this in your main method.
Students[] myStudents = new Students[20];
myStudents[0] = new Students("John", "Richards", 15);
myStudents[1] = new AthleticStudents("Eva", "Grey", 14, 3, 1);
myStudents[2] = new Students("Lena", "Brie", 15);
AthleticStudents addRace= (AthleticStudents)myStudents[1];
addRace.anotherRace(); //This will increment Eva's race count to 4
for (int i = 0; i < 3; i++)
System.out.println(myStudents[i].toString() + "\n\n");
All I did was cast the element into an object AthleticStudents named 'addRace'. By casting myStudents[1] to this new object you are able to access all of AthleticStudents methods.
I just saw the other answer posted which works just as well!
Hope this helps!
I’m not sure that i understand your question, because you are a bit inconsistent with your capitalization. runStudents is a class, while AthleticStudents is both a class and an array. But i’ll try.
IF i did understand your question, you have an array Student[] studentArray. Some Student objects in studentArray are AthleticStudents, others are not. You have a specific AthleticStudent eva which is in studentArray[] having let’s say index 1, and you want to add to her anotherRace(). Your call studentArray[1].anotherRace does not compile because the compiler treats that element as a Student and not as a AthleticStudent.
The trick is to cast the element to AthleticStudent. I omit the test of the element of being really an AthleticStudent; you will have to do that test in your code.
((AthleticStudent) studentArray[1]).anotherRace();
I'm new to Java and i've been bashing my head over the wall to solve this problem. Anyway below is a class that creates a Person and below that, is a class that creates a Phonebook using an ArrayList of type Person. I want to write the remove function (in order to remove a Person from the list) but my problem is that since i only get the name of the person i can't use the Indexof function (cause it requires object) to get at what position lies the name.
This is my first time using an ArrayList to store an Object so i'm not even sure
how my results would appear. I'm guessing that if the position of the name (in my list) is 10 then 11 would be the phone and 12 would be the address. Am i correct?
public class Person
{
private String name;
private String phone;
private String address;
public Person (String n, String p, String a)
{
this.name = n;
this.phone = p;
this.address = a;
}
public void setPhone(String newPhone)
{
this.phone = newPhone;
}
public String getName()
{
return this.name;
}
public String getPhone()
{
return this.phone;
}
public String getAddress()
{
return this.address;
}
public String print()
{
return "Name is : " + this.name + "\nPhone is : " + this.phone + "\nAddress is : " + this.address;
}
}
import java.util.*;
public class phoneBook
{
Scanner in = new Scanner ( System.in );
private ArrayList <Person> persons = new ArrayList <Person>();
private int i;
private boolean flag;
public void addPerson(Person p)
{
persons.add(p);
}
public void listPersons ()
{
System.out.println(persons);
}
public void lookUp (String theName)
{
flag = persons.contains(theName);
if ( flag == true )
{
System.out.println("That name exists!");
}
else
{
System.out.println("That name does not exist!");
}
}
public void remove (String theName)
{
}
Edit: I'm planning to use the Scanner in another function. Don't worry about it.
I'm not sure of if do you want to get the object of that array, but each object is indexed to that array (with full attributes), now you can remove it by using the following code,
public String removePerson(ArrayList<Person> arrayList,String name)
{
for(Person currentPerson:arrayList)
{
if(currentPerson.getName().equals(name))
{
arrayList.remove(currentPerson);
return "Removed successfully"
}
}
return "No record found for that person";
}
just pass the arrayList and the name of that person to this method
You should override the equals() and hashCode() methods in the Person class. This way you will define when two objects of this type will be considered equal. Then you can use list.contains(yourObject) to determine if that object is equal to any object in your list, this based on your equals() implementation.
Does this help you?
public void remove (String theName,ArrayList<Person> persons) {
for (int i = 0; i < persons.size();++i) {
if(persons[i].getName().equals(theName)) {
persons.remove(i);
}
}
}
Best regards, Nazar
In my code below, I am experiencing a problem I am unable to get around... when I add a class Person object to an array, it appears to add fine, however when I attempt to print out that object value form a specified array position, it outputs "null."
Here is the code
import java.util.Scanner;
import java.util.Arrays;
import java.lang.String;
public class Main
{
public static void main(String[] args)
{
int ARRAY_LENGTH = 2;
Scanner in = new Scanner(System.in);
Person[] Persons;
Persons = new Person[ARRAY_LENGTH];
for (int i = 0; i < ARRAY_LENGTH; i++)
{
System.out.println("Enter a name to add to the array: ");
Persons[i] = new Person(in.next());
System.out.println(Persons[i]);
}
Arrays.sort(Persons);
for (int i = 0; i < ARRAY_LENGTH; i++)
{
System.out.println(Persons[i]);
}
}
}
&
public class Person implements Comparable<Person>
{
private String name;
public Person (String aName)
{
String name = aName;
}
public String getName()
{
return name;
}
public int compareTo(Person o)
{
Person other = (Person) o;
if (this.name.equals(o.name))
{
return 0;
}
if (this.name.compareTo(o.name) < 0)
{
return -1;
}
return 1;
}
#Override
public String toString()
{
return name;
}
}
No, it hasn't added null to the array. It's put a reference to a Person object in the array, and when you call toString() on that Person object, it's returning the value of the name field... which is always null, because of this constructor:
public Person (String aName)
{
String name = aName;
}
That isn't assigning a value to the name field - it's declaring a local variable called name. (I'd expect a decent IDE to issue a warning about that.)
You want:
public Person (String aName)
{
name = aName;
}
The constructor
public Person (String aName)
{
String name = aName;
}
stores the name in a local variable.
Change this to
public Person (String aName)
{
this.name = aName;
}
The constructor is wrong
public Person (String aName)
{
String name = aName;
}
it is creating a new variable instead of assigning the field properly.
Try removing the type declaration:
public Person (String aName)
{
name = aName;
}
Let say I have an ArrayList<Student> contains 4 Students(name , city, school).
For example:
1. John Nevada BBBB
2. Mary Ander AAAA
3. Winn Arcata CCCC
4. Ty Artes BBBB
If user enter “BBBB” then it displays: :
1. John Nevada BBBB
2. Ty Artes BBBB
My question is that how do I compare a input string “BBBB” with the schools in the above ArrayList?
Thank you for any help that you guys would provide!
public class Student
{
private String name;
private String city;
private String school;
/**
* Constructor for objects of class Student
*/
public Student(String name, String city, String school)
{
this.name = name;
this.city = city;
this.school = school;
}
public String getSchool(String school)
{
return this.school = school;
}
public String toString()
{
return "Name: " + name + "\tCity: " +city+ "\tSchool: "+school;
}
}
public class AllStudent
{
// instance variables - replace the example below with your own
private ArrayList<Student> listStudent = new ArrayList<Student>();
/**
* Constructor for objects of class AllStudent
*/
public AllStudent() throws IOException
{
//variables
// read an input file and save it as an Arraylist
fileScan = new Scanner (new File("students.txt");
while(fileScan.hasNext())
{
//.......
listStudent.add(new Student(name,city,school);
}
//now let user enter a school, the display name, city, school of that student.
//i am expecting something like below...
public void displayStudentBasedOnSchool(String school)
{
for (i = 0; i < listStudent.size(); i++)
{
//what should i put i here to comapre in input School with school in the listStudent>
}
}
}
Assuming your student is modelled like this (AAAA, BBBB values are stored in blah field):
public class Student {
private String name;
private String state;
private String blah;
//getters & setters..
}
The simplest (not most efficient way) is just to loop the array list and compare the query string with value of blah field
for(Student s : studentList) {
if(s.getBlah().equals(queryString)) {
// match!..
}
}
I believe Student is class and you are creating list of Student
The ArrayList uses the equals method implemented in the class (your case Student class) to do the equals comparison.
You can call contains methods of list to get matching object
Like,
public class Student {
private String name;
private String city;
private String school;
....
public Student(String name, String city, String school) {
this.name = name;
this.city = city;
this.school = school;
}
//getters & setters..
public String setSchool(String school) {
this.school = school;
}
public String getSchool() {
return this.school;
}
public boolean equals(Object other) {
if (other == null) return false;
if (other == this) return true;
if (!(other instanceof Student)) return false;
Student s = (Student)other;
if (s.getSchool().equals(this.getSchool())) {
return true; // here you compare school name
}
return false;
}
public String toString() {
return "Name: " + this.name + "\tCity: " + this.city + "\tSchool: "+ this.school;
}
}
Your array list would be like this
ArrayList<Student> studentList = new ArrayList<Student>();
Student s1 = new Student(x, y, z);
Student s2 = new Student(a, b, c);
studentList.add(s1);
studentList.add(s2);
Student s3 = new Student(x, y, z); //object to search
if(studentList.contains(s3)) {
System.out.println(s3.toString()); //print object if object exists;
} // check if `studentList` contains `student3` with city `y`.It will internally call your equals method to compare items in list.
Or,
You can simply iterate object in studentList and compare items
for(Student s : studentList) {
if(s.getSchool().equals(schoolToSearch)) {
// print object here!..
}
}
Or, as you commented ,
public void displayStudentBasedOnSchool(String school){
for(int i = 0; i < studentList.size(); ++i) {
if(studentList.get(i).getSchool().equals(school)) {
System.out.println(studentList.get(i).toString()); // here studentList.get(i) returns Student Object.
}
}
}
Or,
ListIterator<Student> listIterator = studentList.listIterator(); //use list Iterator
while(listIterator.hasNext()) {
if(iterator.next().getSchool().equals(school)) {
System.out.println(listIterator.next());
break;
}
}
or even,
int j = 0;
while (studentList.size() > j) {
if(studentList.get(j).getSchool().equals(school)){
System.out.println(studentList.get(j));
break;
}
j++;
}
So now you have set of options
for-loop
for-each loop
while loop
iterator
I would probably use Guava library from Google.
Take a look at this question: What is the best way to filter a Java Collection? It provides many excelent solutions for your problem.
Say there is an EmployeeList that contains 5 Employee object.
I want to perform a clone of that EmployeeList to make a new EmployeeList, and I am wondering how should I do that?
So the following is my class Employee:
public class Employee {
private String name;
private String ssn;
private double salary;
private String name() {
return name;
}
private void name(String name) {
this.name = name;
}
private String ssn() {
return ssn;
}
private void ssn(String ssn) {
this.ssn = ssn;
}
private double salary() {
return salary;
}
private void salary(double salary) {
this.salary = salary;
}
void initialize(String initName, String initSsn, double initSalary) {
this.name(initName);
this.ssn(initSsn);
this.salary(initSalary);
}
public Employee(String name, String ssn, double salary) {
this.initialize(name, ssn, salary);
}
public Employee clone() {
return new Employee(this.name, this.ssn, this.salary);
}
}
And the following is my class EmployeeList:
public class EmployeeList implements Cloneable {
private Employee[] list;
private int MAX = 5;
public EmployeeList() {
list = new Employee[MAX];
for (int i = 0; i < MAX; i++)
list[i] = null;
}
public void add(Employee employee) {
list[count] = employee;
}
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException c) {
System.out.println(c);
return null;
}
}
}
I shorten the code so it`s easier to see.
My problem is:
When I performed the copy, I think that it copied the EmployeeList with pointers that points to the original Employee objects. Because when I change the original objects, the one in the new list changes as well
Is there anyway I can get that fixed?
Thank you very much.
yup, it did exactly what you thought it did - it cloned your array including its values. the array values in this case are pointers to instances of Employee, so you got a 2nd array pointing to the same Employees. its called a shallow copy. if you want a full copy you need something like
public Object clone() {
try {
EmployeeList copy = (EmployeeList) super.clone();
if (list!=null) {
copy.list = new Employee[list.length];
for (int i=0; i<list.length; i++) {
copy.list[i] = (Employee)list[i].clone();
}
} else {
copy.list = null;
}
return copy;
} catch (CloneNotSupportedException c) {
System.out.println(c);
return null;
}
}
you will also need to make Employee clonable.
generally when youre dealing with a graph of objects each object's clone() method needs to recursively clone its data members until you hit primitives (like your double) or immutable classes (classes that cannot be changed once constructed - like String in your case)
in your EmployeeList.cone(), insted of calling super.clone(), which does shallow copy, you should instead iterate over the list elements and called clone() on each Employee object, like pseudocode below:
EmployeeList.clone() {
EmployeeList newList = (EmployeeList) super.clone();
int i=0;
for (Employee emp: this.list){
newList[i++] = (Employee) emp.clone();
}
return newList;
}
Other option, without using Cloneable is to use Serializable interface and use a utility like Apache commons SerializationUtils to deep clone the object http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/SerializationUtils.html#clone%28java.io.Serializable%29