equals() method not working - java

The equals() method should check if the dimensions of the first box and the cube are the same. How to fix it? It currently does not work.
The program returns the message "illegal start of type" at if. I am new to this plz help
public class testNew
{
public static void main (String []args)
{
Rectangle3 one = new Rectangle3(5,20);
Box3 two = new Box3(4,4,4);
Box3 three = new Box3(4,10,5);
Cube3 four = new Cube3(4,4,4);
showEffectBoth(one);
showEffectBoth(two);
showEffectBoth(three);
showEffectBoth(four);
}
public static String showEffectBoth(Rectangle3 r)
{
return System.out.println(r);
}
boolean b = two.equals(four);
if (b == true)
{
System.out.println("Box and cube have the same dimensions");
}
}
public class Rectangle3
{
// instance variables
int length;
int width;
public Rectangle3(int l, int w)
{
length = l;
width = w;
}
public int getLength()
{
return length;
}
public int getWidth()
{
return width;
}
public String toString()
{
return getClass().getName() + " - " + length + " X " + width;
}
public boolean equals(Rectangle3 obj)
{
if ((getLength().equals(obj.getLength()) && getWidth().equals(obj.getWidth())))
return true;
else
return false;
}
}

First, regarding the compiler error you have, it has nothing to do with the equals() method. It's only because all of the code below, should be inside your main method as it's the only part where you are declaring the variablestwo and four:
boolean b = two.equals(four);
if (b == true) {
System.out.println("Box and cube have the same dimensions");
}
Notice also, that the Rectangle3 class shouldn't be in the same file as testNew as both are declared public, if you want to use both of them in the same file then you need to remove the public declration from one of them (the one you will not use as filename)
Second, your equals() method is technically correct (I guess functionally as well) but it's not the equals() method you included in your code here, because this one belong to Rectangle3 while the equals() you are testing here should be defined in Box3 and Cube3
NB: Please notice as per assylias's comment, that because b is a boolean there is no need to use if (b == true), just if (b) will be sufficient

It is not the equals function. The line
boolean b = two.equals(four)
Is illegal. It is not within any method and it references variables declared in main()!

Related

Variable Hiding confusion?

So this is basically my code
abstract class B
{
int x = 3;
B()
{
x+=2;
System.out.print("-x" + x + "\n"); // print -x5
x++; // 5 then 6
}
abstract int calculate();
abstract int calculate(int i);
}
class A extends B
{
int x = 2;
A()
{
System.out.print("-x" + calculate(2)+"\n");
}
#Override
int calculate()
{
return x;
}
#Override
int calculate(int i)
{
return(calculate()+i);
}
}
public class Test2 extends A
{
Test2()
{
x+=3;
}
#Override
int calculate()
{
return x + 6;
}
public static void main(String[] args) {
Test2 sub = new Test2();
System.out.print("-x" + sub.calculate()+"\n");
}
}
My problem here is after digging up about variable hiding I learned that if a instance variable is of the same name in both parent class and child class then the childclass hides the instance variable of the parent class. Also I have the prior knowledge that variables cannot be overridden when child class inherits parent class.
So now coming to the problem, in the code when A extends to B, why does the print statement inside constructor A() gives a value -x10? shouldn't it be -x8?? I dont understand how the variable is being changed here. I am new to java so any kind of knowledge will be greatly appreciated. :)
Ok so I have done some debugging and found that the calculate(void) method in class A returns 8. But how is that possible shouldn't it return 6? Please help!
The reason it prints -x10 is because A::calculate(2) calls the Test2::calculate(), which uses A::x to do the calculation.
The sequence of calls that happens is the following:
Test2() {
A()
B() {
B::x = 3
B::x += 2
System.out.print("-x" + x + "\n"); // print -x5
B::x++ // B::x is now 6
}
A::x = 2
System.out.print("-x" + calculate(2)+"\n")
A::calculate(2) {
return(calculate()+2);
Test2::calculate() {
return A::x + 6; // A::x is 2 here, so returns 8
}
} // returns calculate()+2, so returns 10
}
A::x += 3
}
I hope this is just code to test things out, because you should never allow this to happen in real code. You should never allow a method of a subclass to be called from the constructor of a base class, because the subclass is not initialised at that time. The Java compiler does its best to prevent that, but sometimes it does not detect it.
It is returning 8 because:
The line you called System.out.print("-x" + sub.calculate()+"\n"); in class A calls
#Override
int calculate()
{
return x + 6;
}
in class A still, which is incrementing the instance variable int x = 2 in class A . this variable overwrote the one in class B
Hence 2+6 = 8

Redefinition Overriding in Java

We got the following exercice in our last exam, and I don't understand the right answers except the 1st one.
Here is it:
public class Gran {
private int x;
public Gran() { this.x = 68; }
public int age() { this.x = this.x+1; return this.x; }
#Override
public String toString() { return "Gran " + age(); }
}
public class Dad extends Gran {
private int x;
public Dad() { this.x = 41; }
#Override
public String toString() { return "Dad " + age(); }
}
public class Bro extends Dad {
private int x;
public Bro() { this.x = 21; }
#Override
public int age() { System.out.print("Bro "); return x; }
}
public class Sis extends Dad {
private int x;
public Sis() { this.x = 17; }
#Override
public int age() { System.out.print("Sis "); return super.age() - x; }
#Override
public String toString() { return "Sis " + super.toString(); }
}
What would be the correct print-outs if we call this:
Gran[] family = new Gran[] {new Gran(), new Dad(), new Bro(), new Sis()};
for (Gran member : family) System.out.println(member.toString());
It would be really helpful for me, if you tell me the logic behind the right answers.. I got really confused when I checked them!
You should check out the spec.
Especially Example 8.4.8.1-1. Overriding:
class Point {
int x = 0, y = 0;
void move(int dx, int dy) { x += dx; y += dy; }
}
class SlowPoint extends Point {
int xLimit, yLimit;
void move(int dx, int dy) {
super.move(limit(dx, xLimit), limit(dy, yLimit));
}
static int limit(int d, int limit) {
return d > limit ? limit : d < -limit ? -limit : d;
}
}
The caption says:
Here, the class SlowPoint overrides the declarations of method move of class Point with its own move method, which limits the distance that the point can move on each invocation of the method. When the move method is invoked for an instance of class SlowPoint, the overriding definition in class SlowPoint will always be called, even if the reference to the SlowPoint object is taken from a variable whose type is Point.
So with that in consideration, lets look at your example.
The hierarchy is:
Dad is a Gran
Bro is a Dad
Sis is a Dad
The declared type of all of the objects is Gran because of the line Gran[] family = new Gran[] {new Gran(), new Dad(), new Bro(), new Sis()}; That is the same as saying that the reference to each of the objects in the array are taken from a variable whose type is Gran.
Now you will call toString() on each of the elements in the family array. The first is Gran.toString(). When that object was created its x variable was initialized to 68. So the Gran.toString() method will build a String that is first "Gran" then call the age() method which increments x by one then returns the value of x which is 69 at this point. The + operator implicitly creates a new String that coerces the int to a String giving a String "Gran 69".
Next Dad.toString is very similar to Gran. Notice that it starts with the String "Dad" then calls age() which is inherited from Gran. So the output should be "Dad 69". The trick here is that the x variable is private scope, so the x in Dad is a different x then in Gran. That is the same for all of the classes.
For Bro, this class is a Dad, and Dad is a Gran. There is no overridden toString here so Dad.toString() gets used. That makes a String "Dad" then calls Bro.age() this prints "Bro" then returns the x from Bro to create a new String "Dad 21". The line is will look like "Bro Dad 21" because the print of "Bro" happens before the print of "Dad 21".
As for Sis this one is the toughest one. You should take everything from above and convince your self of how Overriding and scoping works. Good luck! I hope this helps.

Object Creation in java and finalize

class FDemo {
int x;
FDemo(int i) {
x = i;
}
protected void finalize() {
System.out.println("Finalizing " + x);
}
void generator(int i) {
FDemo o = new FDemo(i);
System.out.println("Creat obj No: " + x); // this line
}
}
class Finalize {
public static void main(String args[]) {
int count;
FDemo ob = new FDemo(0);
for(count=1; count < 100000; count++)
ob.generator(count);
}
}
}
In the line i have commented, the value of x always shows 0(value of x in object ob), why isnt showing the value of object o?? i know if i use o.x i ll be getting the value of x in object o. But still in this code why does it show the value of abject ob rather than object o??
If you want to reference the x in the FDemo you've just created, you should add a getX() function and call that instead of x, like David Wallace said. (I prefer using getters instead of .variable).
Add this to your class:
public int getX(){
return x;
}
And change your problematic line to this:
System.out.println("Creat obj No: " + o.getX());
That should fix it. As a side note, it's considered good practice to explicitly declare whether your variables and methods are private, public or protected.

Defining a comparator for a quadratic function object

This is my assignment,
a) Write a quadraticFunction that represents a quadratic ax^2 + bx + c with int coeffients a, b, c. Provide a constructor with 3 int parameters for a, b, c. Provide a method double valueAt(double x) returns the value of this quadratic function at x. Also provide a toString method.
b) override the equals method quadraticmethod class. two quadraticfunction should be considered equal if their respective coeffiecients are equal
c) Make the function objects comparable. The compareTo should first compare 1 if equal compare b if equal compare c
d) Define a comparator class for comparing two QuadraticFunction objects. Provide two constructors: a no-argss constructor and a constructor that takes 1 double parameter. When a comparator is created by the no-args constructor, it should compare two quadraticFunction based on their values at x = 0; when a comparator is created by the constructor with a parameter x, it should compare quadraticFunction based on their values at x
Here's my code
I need help with part D, I don't know how to do some of it
public class Ex4
{
int a;
int b;
int c;
public Ex4(int x, int y, int z)
{
a = x; b=y; c=z;
}
public String toString()
{
String X="";
X= X+a+"x^2"+b+"x"+ "+" + c;
return X;
}
public double valueAt(double x)
{
return (a*x*x+b*x+c);
}
//////// Part B
public boolean equals( Ex4 qf )
{
return(this.a==qf.a && this.b==qf.b && this.c==qf.c);
}
/////Part c
// public int compareTo(Ex4 other)
// {
// if (a.equals(other.a))
// {
// if (b.equals(other.b))
// return c.compareTo(other.c);
// return b.comapreTo(other.b);
// }
// return a.compareTo(other.a);
// }
public int compareTo(Ex4 other)
{
if (a > other.a)
return 1;
else if (a < other.a)
return -1;
else if (b > other.b)
return 1;
else if (b < other.b)
return -1;
else if (c > other.c)
return 1;
else if (c < other.c)
return -1;
else
return 0;
}
////Part d
public static void main(String[] args)
{
System.out.println(new Ex3(1, -5, 6));
}
}
Also in the uncomment the area of code under part c, it says int cannot be dereferenced on line 29, 31, 32,33, and 35
Thanks for the help
You can't call methods on primitives, plain and simple.
A better option is to use Integer's static method, Integer.compare(int a, int b) to compare two ints.
First, writing a custom Comparator isn't too terribly difficult; you need to understand the basic structure of one.
Here's the idea: it reads kind of like you're writing a Comparable entity.
class CustomComparator implements Comparator<Ex4> {
#Override
public int compare(Ex4 left, Ex4 right) {
// Compare the entities as specified by the assignment
}
}
Then, you need to accept that as a constructor argument. That, I leave as an exercise to the reader.
Now, to the syntax issue: you're treating primitive int as an Integer, which does have an equals method on it. Primitives aren't objects, hence they can't be dereferenced. You'll want to use the normal equivalence operators (==, >, <) in this situation. You have this already solved in your second-defined compareTo method.
EDIT: After re-reading your requirements, I'm starting to think that your primitive fields are not the right way to go. You should:
Change your fields from int to Integer
Implement Comparable<Ex4> on your entity class
Rely on the default behavior of compareTo() for Integer; that is, your commented code should "just work" (save for the misspell when comparing against C)
Move the secondary compareTo to its own Comparator entity, as described above.
Try this
import java.util.Comparator;
public class Ex4Comparator implements Comparator<Ex4> {
private double x = 0.0;
public Ex4Comparator() {
}
public Ex4Comparator(double x) {
this.x = x;
}
#Override
public int compare(Ex4 o1, Ex4 o2) {
return Double.compare(o1.valueAt(x), o2.valueAt(x));
}
}
Also your equals method doesn't override Object's equals method. You may want to change it to something like
#Override
public boolean equals(Object o) {
if (o instanceof Ex4) {
Ex4 other = (Ex4)o;
return (a == other.a && b == other.b && c == other.c);
}
return false;
}

Is String not considered an object?

What I do not understand is why I am getting an error compiling my code when a String is in fact an object, and the compiler is saying otherwise. I dont know why I keep getting this error message
symbol: method compareTo(Object)
location: variable least of type Object
.\DataSet.java:17: error: cannot find symbol
else if(maximum.compareTo(x) < 0)
here is the code. I'm trying to utilize the class comparable to allow two objects to use the compareTo method. In the tester, I'm just trying to use a basic string object to compare.
public class DataSetTester
{
public static void main(String[] args)
{
DataSet ds = new DataSet();
String man = "dog";
String woman = "cat";
ds.add(man);
ds.add(woman);
System.out.println("Maximum Word: " + ds.getMaximum());
}
}
Class:
public class DataSet implements Comparable
{
private Object maximum;
private Object least;
private int count;
private int answer;
public void add(Object x)
{
if(count == 0){
least = x;
maximum = x;
}
else if(least.compareTo(x) > 0)
least = x;
else if(maximum.compareTo(x) < 0)
maximum = x;
count++;
}
public int compareTo(Object anObject)
{
return this.compareTo(anObject);
}
public Object getMaximum()
{
return maximum;
}
public Object getLeast()
{
return least;
}
}
Comparable Interface:
public interface Comparable
{
public int compareTo(Object anObject);
}
Of course String is an Object.
Comparable is generic now. Why do you feel the need to make those references Object if they are type String? Your code is poor; it's not a Java problem.
I don't see why DataSet needs to implement Comparable. You just need to compare incoming Strings as they're added. Do it this way and you'll fare better:
public class DataSet {
private String maximum;
private String least;
private int count;
private int answer;
public void add(String x) {
if(count == 0){
least = x;
maximum = x;
} else if (least.compareTo(x) > 0) {
least = x;
} else if(maximum.compareTo(x) < 0) {
maximum = x;
}
count++;
}
public String getMaximum() { return this.maximum; }
public String getLeast() { return this.least; }
public int getCount() { return this.count; }
}
The problem is that DataSet implements Comparable, but Object doesn't.
Instead of storing Objects, you want to store Comparables. However, if you do get this to compile, you will get into an infinite loop right here:
public int compareTo(Object anObject)
{
// Yeah, never stop loopin'!
return this.compareTo(anObject);
}
It's recommended that in newer code, you use the generic Comparable<T> interface. Your code would then look like this:
public class DataSet implements Comparable<DataSet>
{
private String maximum;
private String least;
private int count;
private int answer;
public void add(String x)
{
if(count == 0){
least = x;
maximum = x;
}
else if(least.compareTo(x) > 0)
least = x;
else if(maximum.compareTo(x) < 0)
maximum = x;
count++;
}
public int compareTo(DataSet anObject)
{
// I don't really know how you want this to work.
// Come up with your own criteria on what makes a DataSet greater or less than
// another one.
count - anObject.count
}
// Good practice to include this if you're doing a compareTo.
#Override
public boolean equals(Object other)
{
return (other instanceof DataSet) && compareTo((DataSet)other) == 0;
}
public String getMaximum()
{
return maximum;
}
public String getLeast()
{
return least;
}
}
Edit - just saw that you're comparing strings. In that case, you don't really need DataSet to implement Comparable. However, if you do need it for something else, what I wrote still stands.
least and maximum are simply Objects, and the Object class doesn't have a compareTo(...) method, simple as that. least and maximum need to be declared Comparable, not Object. And as written, it makes no sense declaring DataSet to implement the Comparable interface since there are no DataSet objects present and certainly none being compared.
java.lang.Object does not have a compareTo() method.
First of all there is an infinite loop in you code:
public int compareTo(Object anObject)
{
return this.compareTo(anObject);
}
this method is continuously calling itself.
Regarding your compile error: you have declared variable as Object, which obviously does not have a compareTo method.
There is no compareTo() method in Object. I guess you're looking for String.compareTo().
Type checking is done at compile time and not runtime. At compile time, least and maximum are considered to be objects of type Object and not String.

Categories

Resources