I need to make an add(Length) method that return a new length that is equal in size to the sum of the sizes of this length and the argument. I am unsure whether I need to return a double or Length and how to add
public class Length implements Comparable<Length>{
private final double length; //private! Do NOT add a getter
// This constructor must remain private
private Length(double l){
length = l;
}
public double add(Length l){
return ;
}
public double subtract(Length l){
}
public double scale(double d){
}
public double divide(Length l){
}
public double Length(Position one, Position two){
}
// TODO: For all constants, have a line:
// public static final Length ... = new Length(...);
// Use the #Override annotation on all methods
// That override a superclass method.
#Override
public boolean equals(Object other){
//TODO
}
#Override
public int hashCode(){
//TODO
}
#Override
public String toString(){
//TODO
}
// If you are overriding a method from an interface, then Java 5
// says you CANNOT use Override, but Java 6 says you MAY. Either is OK.
// #Override
public int compareTo(Length other) {
//TODO
}
// TODO Write the rest of the methods for this class, and
// the other two classes.
}
It depends on your requirement, but typically you'd want to return a new Length object.
public Length add(Length other){
// check that other is not null
return new Length(this.length + other.length);
}
You would do something similar for all the other mathematical methods.
As Rohit has stated in their comment, this makes your class immutable since there is no method that can modify the length field (but instead return a new Length object).
Related
I need to make a programm which is like a rally, theres 2 types of vehicles, motorcycle and cars, two types of motorcycle, with and without sidecar, the thing is that I need to verify if there is just a motorcycle in an array list, I mean, two wheels vehicle. That verification should be done in a method called esDe2Ruedas(), which is called by an abstract overrided method called check() that should be the one that verifies if a group of vehicles from an array are able to run in the rally, if its true all the elements of the array must be from the same type.
Here is the code
this is how the program arrays the vehicles
GrandPrix gp1 = new GrandPrix();
gp1.agregar(v1);
//gp1.mostrar(v1);
gp1.agregar(v2);
System.out.println(gp1.check());
GrandPrix gp2 = new GrandPrix();
gp2.agregar(vt1);
gp2.agregar(vt2);
gp2.agregar(m2);
System.out.println(gp2.check());
GrandPrix gp3 = new GrandPrix();
gp3.agregar(vt1);
gp3.agregar(vt2);
gp3.agregar(m1);
System.out.println(gp3.check());
GrandPrix gp4 = new GrandPrix();
gp4.agregar(m1);
gp4.agregar(m2);
System.out.println(gp4.check());
This is the class that is using
import java.util.ArrayList;
public class GrandPrix extends Rally{
ArrayList<Vehiculo> ve = new ArrayList<Vehiculo>();
public void agregar(Vehiculo v) {
ve.add(v);
}
public void agregar(Carro c) {
ve.add(c);
}
public void agregar(Moto m) {
ve.add(m);
}
#Override
boolean check() {// HERE I VERIFY IF THE VEHICLES ARE COMPATIBLE
return false;
}
}
This is the class where everything goes on
public class Vehiculo {
private String Nombre;
private double velocidad_max;
private int peso;
private int comb;
public Vehiculo() {
setNombre("Anónimo");
setVel(130);
setPeso(1000);
setComb(0);
}
public Vehiculo(String string, double d, int i, int j) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
}
double rendimiento() {
return velocidad_max/peso;
}
public boolean mejor(Vehiculo otroVehiculo) {
return rendimiento()>otroVehiculo.rendimiento();
}
public String toString() {
return getNombre()+"-> Velocidad máxima = "+getVel()+" km/h, Peso = "+getPeso()+" kg";
}
/**************************************
---------SET And GET Nombre------------
***************************************/
public String getNombre() {
return Nombre;
}
public void setNombre(String nuevoNombre) {
this.Nombre=nuevoNombre;
}
/**************************************
---------SET And GET velocidad_max------------
***************************************/
public double getVel() {
return velocidad_max;
}
public void setVel(double nuevaVel) {
this.velocidad_max=nuevaVel;
}
/**************************************
---------SET And GET peso------------
***************************************/
public double getPeso() {
return peso;
}
public void setPeso(int nuevoPeso) {
this.peso=nuevoPeso;
}
/**************************************
---------SET And GET comb------------
***************************************/
public int getComb() {
return comb;
}
public void setComb(int comb) {
this.comb = comb;
}
boolean esDe2Ruedas() {
return false;
}
}
This is the class of motorcycles, which is in theory the same as the car's class, without sidecar thing
public class Moto extends Vehiculo{
private boolean sidecar;
public Moto(String string, double d, int i, int j) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
setSidecar(false);
}
public Moto(String string, double d, int i, int j, boolean b) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
setSidecar(b);
esDe2Ruedas(false);
}
public String toString() {
String str = null;
if(isSidecar())
str =super.toString()+", Moto, con sidecar";
else
str =super.toString()+", Moto";
return str;
}
public boolean isSidecar() {
return sidecar;
}
public void setSidecar(boolean sidecar) {
this.sidecar = sidecar;
}
I guess what you presented is what is given. If you came up with the design it is ok, but I believe it could be improved. Anyway, I try to respond to what I believe was your question straight away.
Vehiculo is the super type of Moto (which can have a side car and becomes 3 wheeler).
Vehiculo has a method esDe2Ruedas, which returns false.
Moto inherits that method <-- this is wrong, it should override it and, depending on side car, return the expected boolean value.
In the check method you can now distinguish between Moto and "Moto with sidecar" by using that method.
I created an abstract class Fruit, which overrides the equals() method. Then I created a subclass, Orange, which overrides the copy() and the equals() method. In my test file, TestFruit.java, I am creating an array of oranges and testing their methods. I am trying to create a deep copy of orange and do a deep comparison between the parent orange and the copy. However, in my output, the comparison always returns false. I checked the parent and the copy's attributes and they do seem to be the same. Any pointers would be appreciated. I am pretty new to Java and copying. I attached my code below.
Fruit.java:
package juicer;
import copy.Copyable;
public abstract class Fruit implements Copyable, Cloneable
{
private double mass;
private boolean isJuicedRemoved;
protected Fruit(double theMass)
throws IllegalMassException
{
{
if (theMass <= 0)
{
throw new IllegalMassException(theMass);
}
else
{
this.mass = theMass;
this.isJuicedRemoved = false;
}
}
}
protected Fruit(Fruit fruit)
{
this.mass = fruit.mass;
this.isJuicedRemoved = fruit.isJuicedRemoved;
}
public double getMass()
{
return mass;
}
public boolean getIsJuicedExtracted()
{
return isJuicedRemoved;
}
protected void setMass(double value)
{
this.mass = value;
}
protected abstract double juiceRatio();
public double extractJuice()
{
double liquidMass = amountJuice();
if (!isJuicedRemoved)
{
isJuicedRemoved = true;
mass -= liquidMass;
}
return liquidMass;
}
public double amountJuice()
{
if (isJuicedRemoved) return 0.0;
return mass * juiceRatio();
}
#Override
public boolean equals(Object obj)
{
// Steps to override the equals() method():
// Step 1: Test if obj is an instance of Fruit.
// If it is not, then return false.
if (!(obj instanceof Fruit)) return false;
// Step 2: Cast obj to an Fruit.
Fruit rhs = (Fruit)obj;
// Step 3: Test if the data fields of the invoking object are
// equal to the ones in rhs using a deep comparison
// and return this result.
return super.equals(obj) && // test for equality in the super class
mass == rhs.mass &&
isJuicedRemoved == rhs.isJuicedRemoved;
}
#Override
public int hashCode()
{
int result = super.hashCode();
result = 31*result + Double.hashCode(mass);
result = 31*result + Boolean.hashCode(isJuicedRemoved);
return result;
}
#Override
public Object clone() throws CloneNotSupportedException
{
Fruit objectClone = (Fruit)super.clone();
objectClone.mass = mass;
objectClone.isJuicedRemoved = isJuicedRemoved;
return objectClone;
}
#Override
public String toString()
{
return "\tmass = " + mass +
"\n\tisJuiceExtracted = " + isJuicedRemoved + "\n";
}
}
Orange.java:
package juicer;
public class Orange extends Fruit
{
public Orange(double mass)
{
super(mass);
}
// copy constructor
public Orange(Orange other)
{
super(other);
}
#Override
protected double juiceRatio()
{
return 0.87;
}
#Override
public boolean equals(Object obj)
{
// Steps to override the equals() method():
// Step 1: Test if obj is an instance of Orange.
// If it is not, then return false.
if (!(obj instanceof Orange)) return false;
// Step 2: Cast obj to an Orange.
// This step is not needed since the only data fields this
// class has are the ones it inherits.
// Step 3: Test if the data fields of the invoking object are
// equal to the ones in rhs using a deep comparison
// and return this result.
return super.equals(obj);
}
#Override
public Object copy()
{
return new Orange(this);
}
#Override
public String toString()
{
return "Orange:\n" + super.toString();
}
}
TestFruit.java:
package test;
import juicer.*;
import java.util.Random;
public class TestFruit
{
public static void main(String[] args)
{
Orange[] oranges = new Orange[1];
//Random double generator for mass
Random rd = new Random();
//create oranges
for (int i = 0; i <= oranges.length - 1; i++ )
{
oranges[i] = new Orange(rd.nextDouble());
}
for (Orange orange : oranges)
{
Orange orangeCopy = new Orange(orange);
if (orange == orangeCopy)
{
System.out.print("The comparison is true!");
}
else
{
System.out.print("Does not match.");
}
}
}
}
One of the common misconceptions in Java is the use of == vs .equals(). When you use == to compare two objects in Java, internally it's comparing its memory address. == does not actually call .equals().
In this case, you have two distinct orange objects, so the comparison will always return false.
If you use a.equals(b), then it will actually invoke your equals method which you implemented.
As #Andreas pointed out in the comments, there's another issue. Calling super.equals(obj) in Fruit will call the superclass implementation of equals, and the superclass of Fruit is Object. Object.equals() behaves the same as == (i.e. also checking for reference equality). Overriding .equals() is not trivial, so it can often be nice to have the IDE generate it for you.
In contrast with a language like C++, Java does not have operator overloading. This means that you can't define a different implementation for ==. This is why it's best practice to always call .equals() when comparing any non-primitive types (unless you're explicitly checking reference equality, which is rare).
I am using three classes in my program:
Term class with variables coefficient and exponent, toString() method etc.
Polynome class, using an ArrayList to store the different Term objects.
Main class that runs the program.
Can I use the toString method of ArrayList in my Polynome class? I'm trying to, but I can't.
I need my polynome to output like this: [3x^2, 3x^1, 1x^0]
I am really confused, I'm calling the toString method of Term, using a for-loop to access each term separately.
My code:
public class Term {
private int coëfficiënt;
private int exponent;
public Term(int coëfficiënt, int exponent) {
this.coëfficiënt = coëfficiënt;
this.exponent = exponent;
}
public int getCoef() {
return coëfficiënt;
}
public int getExp() {
return exponent;
}
public String toString() {
return coëfficiënt + "x^" + exponent;
}
}
Polynome class:
public class Polynoom {
private ArrayList<Term> polynoom;
public Polynoom() {
polynoom = new ArrayList<Term>();
}
public void add(Term term) {
polynoom.add(term);
}
public Term get(int i) {
return polynoom.get(i);
}
public int size() {
return polynoom.size();
}
public String toString() {
// what should I write here?
}
}
Main class:
public class opgave3 {
public static void main(String[] args) {
Polynoom polynoom1, polynoom2, sompolynoom;
polynoom1 = new Polynoom();
polynoom1.add(new Term(1, 2));
polynoom1.add(new Term(3, 1));
polynoom1.add(new Term(1, 0));
polynoom2 = new Polynoom();
polynoom2.add(new Term(-1, 3));
polynoom2.add(new Term(2, 2));
polynoom2.add(new Term(-5, 0));
System.out.println("Tests: ");
System.out.println(polynoom1.toString());
for (int i = 0; i < polynoom1.size(); i++) {
System.out.println(polynoom1.get(i).toString());
}
System.out.println(polynoom1.get(0).toString());
}
}
You just need to use your ArrayList's toString() method as the results of Polynome's toString() method.
public class Polynome {
public ArrayList<Term> terms;
#Override
public String toString() {
if (terms != null) {
return terms.toString();
} else {
return "";
}
}
}
EDIT: The quick answer, since you put your code up is to put
return polynoom.toString();
where you have indicated. Then in your Main class you can simply write
System.out.println(polynoom1);
to show the contents in the desired format.
As Tenner said, use the toString() method of your ArrayList to get the desired output. But also make sure your Term class has a useful toString method of its own:
public class Term {
private int co, ex;
public Term(int coeff, int exp) {
co = coeff;
ex = exp;
}
#Override
public String toString() {
return co + "x^" + ex;
}
}
Add #Override toString() to your Term & Polynome class. The Term class toString() should return a string in the format of coefficientx^exponent.
Then have the Polynome class toString() return yourArrayList.toString()
public static void main(String[] args) throws Exception {
Polynome polynome = new Polynome();
polynome.addTerm(3, 2);
polynome.addTerm(3, 1);
polynome.addTerm(1, 0);
System.out.println(polynome);
}
public static class Term {
private int coefficient;
private int exponent;
public Term(int c, int e) {
coefficient = c;
exponent = e;
}
#Override
public String toString() {
return coefficient + "x^" + exponent;
}
}
public static class Polynome {
private List<Term> terms = new ArrayList<>();
public void addTerm(int coefficient, int exponent) {
terms.add(new Term(coefficient, exponent));
}
#Override
public String toString() {
return terms.toString();
}
}
Results:
Long story short, you can ALWAYS use toString() on anything, even if it's a user defined class. When you call the method, it calls the closest parent class's toString() method, which is guaranteed to be there as Object has one. If you want to control the output of toString() called on your object, you must override it. As it is, if you have an object with a member of type ArrayList, calling your object's toString() will include a ton of extra information that you probably don't want. In order to get the output you want, you need to have the code given by #Tenner's answer, which is
public class Polynome {
public ArrayList<Term> terms;
#Override
public String toString() {
if (terms != null) {
return terms.toString();
} else {
return "";
}
}
}
But you also need to override toString() in the Term class, so that each term outputs in the form desired. The reason this is required is that when you call toString() on an ArrayList, or any other container for that matter, it iterates through the container, calling each object's toString() in turn, adding whatever formatting the container class defines. Ultimately, Term's toString() will be called, and you can control that output by overriding it in the Term class.
As for the last part of the question, you need not call Term's toString() directly, as calling the toString() method of the ArrayList will do this on its own.
I am trying to understand the compareTo method. I wrote this class AboutcompareTo, but i am stuck in why/how i get this error?- the code is nearly finished.
anyone can explain in details what i am doing wrong. Thanks
the code:
public class AboutCompareTo {
public static void main(String[] args) {
Fruit[] fruits = { new Fruit(2), new Fruit(3), new Fruit(1) };
java.util.Arrays.sort(fruits);
}
}
class Fruit implements Comparable<Fruit> {
private double weight;
public Fruit(double weight) {
this.weight = weight;
}
#Override
public int compareTo(Fruit o) {
Fruit f = (Fruit) o;
if (Fruit > o.Fruit) // <-- the error
return 1;
else if ((Fruit < o.Fruit)) // <-- the error
return -1;
else
return 0;
}
}
The compareTo method compares an instance of your class, i.e. this Fruit, to an instance of another Fruit passed to you as a parameter. Therefore, the comparison needs to be between o's weight, and your own weight:
#Override
public int compareTo(Fruit o) {
if (this.weight > o.weight)
return 1;
else if (this.weight < o.weight)
return -1;
else
return 0;
}
Note 1: I used this.weight to refer to the weight of this Fruit. I did this to point out that weight attribute belongs to this instance; however, you can omit this. from the expression, i.e. use weight > o.weight instead.
Note 2: I assume that you did this for a learning exercise. For production code Java class library provides a pre-built method for comparing doubles - i.e. Double.compare. You can rewrite the method in a single line:
#Override
public int compareTo(Fruit o) {
return Double.compare(weight, o.weight);
}
Aright, I think i got this going. But now I'm having an issue with the interface methods. The interface method uses a generic type and 1 object. But the assignment calls for adding two objects. I'm now stuck at this point. I'm not sure how to write the add(T o) interface since I can only send one object into the method. I've tried using value1.add(value2) but when I test the values only values for values1 seems to come up. I have no idea where value2 goes Here is my class and the interface
public class MyFraction implements MyMath<MyFraction> {
private List<Character> sign = new ArrayList<Character>();
private List<Integer> numerator = new ArrayList<Integer>();
private List<Integer> denominator = new ArrayList<Integer>();
public MyFraction(int numerator, int denominator, char sign) {
this.numerator.add(numerator);
this.denominator.add(denominator);
this.sign.add(sign);
}
public MyFraction(){}
public static void main(String[] args) {
MyFraction run = new MyFraction();
run.start();
}
private void start() {
char sign = JOptionPane.showInputDialog(null, "Enter - for negative + for positive number ").charAt(0);
int numerator = Math.abs(Integer.parseInt(JOptionPane.showInputDialog(null, "Enter a numerator ")));
int denominator = Math.abs(Integer.parseInt(JOptionPane.showInputDialog(null, "Enter a denominator ")));
MyFraction value1 = new MyFraction(numerator, denominator, sign);
sign = JOptionPane.showInputDialog(null, "Enter - for negative + for positive number ").charAt(0);
numerator = Math.abs(Integer.parseInt(JOptionPane.showInputDialog(null, "Enter a numerator ")));
denominator = Math.abs(Integer.parseInt(JOptionPane.showInputDialog(null, "Enter a denominator ")));
MyFraction value2 = new MyFraction(numerator, denominator, sign);
System.out.println("numerator 1: "+value1.getNumerator() );
System.out.println("denominator 1: "+value1.getDenominator() );
System.out.println("sign 1: "+value1.getSign() );
System.out.println();
System.out.println("numerator 2: "+value2.getNumerator() );
System.out.println("denominator 2: "+value2.getDenominator() );
System.out.println("sign 2: "+value2.getSign() );
}
public int getNumerator(){
int value = this.numerator.get(0);
return value;
}
public int getDenominator(){
int value = this.denominator.get(0);
return value;
}
public char getSign(){
char value = this.sign.get(0);
return value;
}
#Override
public MyFraction add(MyFraction o) {
return null;
}
#Override
public MyFraction subtract(MyFraction o) {
// TODO Auto-generated method stub
return null;
}
#Override
public MyFraction divide(MyFraction o) {
// TODO Auto-generated method stub
return null;
}
#Override
public MyFraction multiply(MyFraction o) {
// TODO Auto-generated method stub
return null;
}
}
public interface MyMath<T> {
public T add(T o);
public T subtract(T o);
public T divide(T o);
public T multiply(T o);
}
An interface is somewhat a contract, that sais "whoever implements me must contain an implementation of all the methods declared in me". Every class that implements that interface figuratevely signs that contract and therefore must have it's own implementation of these methods.
In your class you are missing the implementation of the whole interface, which is why your code is not compiling. Your class should look like:
public class MyFraction implements MyMath<MyFraction> {
....
}
//interface memebers
#Override
public MyFraction subtract(MyFraction o){
//do subtraction here
return null;
}
#Override
public MyFraction divide(MyFraction o){
//do division here
return null;
}
#Override
public MyFraction multiply(MyFraction o){
//do multiplication here
return null;
}
#Override
public MyFraction add(MyFraction o) {
// do adding here
return null;
}
}
Please take a step back and think about the solution you got so far. Your class MyFraction contains four lists - why? "My" MyFraction would consist of a numerator, a denominator and maybe a sign.
Would I choose a Character to store the sign-> I do not know. But you should think about negative values for the numerator and denominator, e.g. numerator is -4 and denominator -2. What value has MyFraction when the sign is entered as "-".
To create a MyFraction instance you should be able to use a constructor like this
public MyFraction(Integer theNumerator, Integer theDenominator, Character theSign)
And remember to implement all methods of the interface. You got only the method add so far and code will not compile because of the missing implementations.