Question
Please help with debugging this class in JAVA!!!! I suppose to return: Yay1 Yay2 Yay3 But my code only return Yay1 Yay3 Could you please
Please help with debugging this class in JAVA!!!!
I suppose to return:
Yay1
Yay2
Yay3
But my code only return
Yay1
Yay3
Could you please help me figure out where i got wrong?
Thanks
import java.util.*;
class Person {
private String name;
private Car currentCar;
public Person(String name, Car currentCar) {
this.setName(name);
this.setCurrentCar(currentCar);
}
public boolean moveToCar(Car c) {
//Tries to move the person from their current car
//to the car passed in as a parameter. If the two
//cars are not adjacent, returns false (and the
//person remains in their current car). Returns
//true if the person was able to move.
//O(1)
c.getPrevious();
if(this.currentCar.equals(c.getPrevious())){
return true;
}else{
return false;
}
}
public boolean equals(Object o) {
//two people are "equal" if they have the same name
//O(1)
//return false;
// If the object is compared with itself then return true
if (o == this) {
return true;
}
/* Check if o is an instance of Complex or not
"null instanceof [type]" also returns false */
if (!(o instanceof Person)) {
return false;
}
// typecast o to Complex so that we can compare data members
Person p = (Person) o;
// Compare the data members and return accordingly
/* if(name.equalsIgnoreCase(p.getName()))
return true;
else
return false;*/
return (p.name == this.name && p.currentCar == this.currentCar);
}
public int hashCode() {
//returns a hashcode for a person...
//remember: if two objects are equal, they should
//have the same hashcode
//O(1)
return this.name.hashCode();
}
public String toString() {
//returns the person's name
//O(1)
return name;
}
//example test code... edit this as much as you want!
public static void main(String[] args) {
Car c1 = new Car("C1");
Car c2 = new Car("C2");
Car c3 = new Car("C3");
c1.setNext(c2);
c2.setPrevious(c1);
Person p1 = new Person("P1", c1);
if(p1.getCurrentCar().equals(c1) && p1.getName().equals("P1")) {
System.out.println("Yay 1");
}
if(p1.moveToCar(c2) && p1.getCurrentCar().equals(c2) && p1.moveToCar(c1) && p1.getCurrentCar().equals(c1)) {
System.out.println("Yay 2");
}
Person p1b = new Person("P1", c1);
if(p1.equals(p1b) && p1.hashCode() == p1b.hashCode()) {
System.out.println("Yay 3");
}
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setCurrentCar(Car currentCar) {
this.currentCar = currentCar;
}
public Car getCurrentCar() {
return currentCar;
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started