Modifying Fraction Class and Test Driver JAVA - java

My Professor has created code that needs to be modified. The only problem is I don't understand his style at all on top of being a fairly new programmer myself. The parameters for the assignment are as follows:
• Modify setters so that they ignore inappropriate values (i.e., divide by zero)
• Implement the equals() method inherited from the top-level Object class
• Implement less than and greater than methods
• Implement add, subtract, and multiply methods
• Makes sure the equals method returns true for any two fractions that are arithmetically equal.
• Make sure that the equals method does not alter the values of the fractions being compared.
• The lessThan and greaterThan methods must each return a Boolean value, not a string.
• The provided reduce method returns a new (reduced) fraction object as its function value
I am completely lost about this assignment as I don't have the slightest clue where to even begin. Any and all help would be greatly appreciated!!!! I have the feeling that once I see it done, it will all make sense to me. I am just not used to this style of teaching at all.
public class Fraction {
private int numer;
private int denom;
public Fraction() { // no-arg constructor
numer = 0;
denom = 1;
}
public Fraction(int numer, int denom) {
this.numer = numer;
this.denom = denom;
}
public Fraction(Fraction frac) { // copy constructor
numer = frac.getNumer();
denom = frac.getDenom();
}
// getters and setters
public int getNumer() {
return numer;
}
public void setNumer(int x) {
numer = x;
}
public int getDenom() {
return denom;
}
public void setDenom(int x) {
denom = x;
}
// Special Methods
public String toString() {
return numer + "/" + denom;
}
// Other Methods
public Fraction reduce() {
Fraction temp = new Fraction();
int GCD = gcd(numer, denom);
temp.setNumer(numer / GCD);
temp.setDenom(denom / GCD);
return temp;
}
// Private Methods
private int gcd(int n1, int n2)
{
int M, N, R;
if (n1 < n2)
{
N = n1;
M = n2;
}
else
{
N = n2;
M = n1;
}
R = M % N;
while (R != 0)
{
M = N;
N = R;
R = M % N;
}
return N;
}
public static void main(String[] args) {
// test constructors
Fraction frac0 = new Fraction();
System.out.println("TESTING NO-ARG CONSTRUCTOR");
System.out.println("frac0: Result should be 0/1:");
System.out.println("Numer = " + frac0.getNumer());
System.out.println("Denom = " + frac0.getDenom());
System.out.println("TESTING int/int CONSTRUCTOR");
Fraction frac1 = new Fraction(2,4);
System.out.println("frac1: Result should be 2/4:");
System.out.println("Numer = " + frac1.getNumer());
System.out.println("Denom = " + frac1.getDenom());
System.out.println("TESTING Fraction CONSTRUCTOR");
Fraction frac2 = new Fraction(frac1);
System.out.println("frac2: Result should be 2/4:");
System.out.println("Numer = " + frac2.getNumer());
System.out.println("Denom = " + frac2.getDenom());
System.out.println("TESTING COPY CONSTRUCTOR frac1  frac2");
if (frac1.getNumer() == frac2.getNumer() &&
frac1.getDenom() == frac2.getDenom() &&
frac1 != frac2)
{
System.out.println("Copy constructor working");
}
else
System.out.println("PROBLEM with copy constructor");
// test equal method
System.out.println("TESTING EQUALITY OF frac1 and frac2 -");
System.out.println("SHOULD BE FOUND EQUAL:");
if (frac1.equals(frac2))
{
System.out.println("frac1 and frac2 found equal");
}
else
{
System.out.println("frac1 and frac2 NOT equal");
}
// test reduce method
System.out.println("TESTING reduce METHOD ON frac1");
Fraction reduced_frac1 = frac1.reduce();
System.out.println("Reduced frac1 = " + reduced_frac1);
// test getters and setters
frac2.setNumer(8);
frac2.setDenom(12);
System.out.println("Numer = " + frac2.getNumer());
System.out.println("Denom = " + frac2.getDenom());
// System.out.println("GCD of 2/4 = " + frac1.gcd(1,4));
}
//* TO BE COMPLETED *
}

There is nothing wrong with his teaching methods and with some further study I am sure you can figure it out. No one here is going to do it for you and I don't want to do your homework so I will ask the common question, what have you tried so far? I've given you one of the modified setters. Keep working, study your java better or you are going to have a hard time when it gets difficult.
//Here is where you start
public void setDenom(int x){
if(x > 0){
denom = x;
}else{
//throw an error
}
}

Related

Cannot figure out error for homework beginning programmer [duplicate]

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 5 years ago.
Need a little help figuring out why the last part of my code gives an error. Can anybody tell me what's wrong? I'm working with NetBeans for an intro level programming class and cant figure out the last bit of why this is wrong.
I'm getting the following error:
Cannot find symbol symbol: variable rat04 location: class Rational
package rational;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Rational {
// the numer and denom fields represent a fraction
// CLASS INVARIANTS:
// CI1: denom is not 0,
// CI2: denom is positive,
// CI3: numer and denom are in lowest terms.
private final int numer;
private final int denom;
//toString and toDouble
public String toString() {
return numer + "/" + denom;
}
public double toDouble() {
return 1.0 * numer / denom;
}
//utility method
private static int greatestCommonDivisor(int a, int b) {
int c;
while (b != 0) {
c = a % b;
a = b;
b = c;
}
return Math.abs(a);
}
private static void testGcd() {
System.out.println("");
System.out.println("Test Greatest Common Denominator");
System.out.println("");
for (int i = -21; i < 31; i += 2) {
for (int j = -17; j < 31; j += 3) {
System.out.printf("\n%5d%5d%5d", i, j, greatestCommonDivisor(i, j));
}
}
System.out.println("");
}
public Rational(int numer, int denom) throws ZeroDenomException {
// CI1. No way to fix, must throw exception.
if (denom == 0) {
throw new ZeroDenomException();
}
// CI2. Can fix.
if (denom < 0) {
numer *= -1;
denom *= -1;
}
// CI3. Can fix.
int gcd = greatestCommonDivisor(numer, denom);
if (gcd != 1) {
numer /= gcd;
denom /= gcd;
}
// all class invariants now satisfied, initialize fields:
this.numer = numer;
this.denom = denom;
}
public Rational(int book) throws ZeroDenomException {
//this(integer, 1);
//this(1, book);
this(book, 1);
}
public Rational() throws ZeroDenomException {
this(0);
}
private static void testClass() throws ZeroDenomException {
System.out.println("Rational tests.");
System.out.println("");
System.out.println("Test C-tor");
System.out.println("Expected outcome: 4/25, -4/25, -4/25," + "4/25 17/1, 0/1.");
System.out.println("");
Rational rat01 = new Rational(144, 900);
Rational rat02 = new Rational(-144, 900);
Rational rat03 = new Rational(144, -900);
Rational rat04 = new Rational(-144, -900);
Rational rat05 = new Rational(17);
Rational rat06 = new Rational();
System.out.println("rat01 = " + rat01);
System.out.println("rat02 = " + rat02);
System.out.println("rat03 = " + rat03);
System.out.println("rat04 = " + rat04);
System.out.println("rat05 = " + rat05);
System.out.println("rat06 = " + rat06);
}
public static void main(String[] args) {
System.out.println("Rational class");
System.out.println("Implemented by (My Name)");
try {
testClass();
//testGcd();
} catch (ZeroDenomException ex) {
System.out.println("Zero demon exception in testClass()! (J:H)");
}
System.out.println("");
System.out.println("Try bad input");
try {
Rational rat00 = new Rational(0, 0);
} catch (ZeroDenomException zde) {
System.out.println(" Expected Zero Denominator Exception. " + zde);
} catch (Exception e) {
System.out.println("Should not be a general Exception.");
}
System.out.println("");
System.out.println("");
System.out.println("Test toDouble. Expect 0.16");
System.out.println("rat04 to double: " + rat04.toDouble());
}
}
You declared rat04 in testClass and use it in main. The scopes are different.
You can't use a variable from one scope to another.
You can create a static variable in the class (member variable) to be accessible from both method if you want (but really should not...)
public class Rational {
static Rational rat04;
...
}
Or simply don't print the value in main but in testClass where it belong.

How to print out a toString for this class?

I have written a polynomial class and a tester class. The polynomial class can evaluate and return the sum of the polynomial when the degree, coefficients and the value of x are provided. Basically I need to edit my toString method so it actually prints out the polynomial
import java.util.Arrays;
import java.util.Scanner;
public class Polynomial {
private int degree;
private int [] coefficient;
private double evaluation;
private double sum;
private double value;
Scanner key = new Scanner(System.in);
public Polynomial(int degree)
{
this.degree = degree;
coefficient = new int [degree+1];
}
public void setCoefficient(int coefficient)
{
this.coefficient[this.degree] = coefficient;
}
public int getCoefficient(int degree)
{
return coefficient[degree];
}
public double Evaluate(double value)
{
this.value =value;
for (int i=0; i<=degree; i++)
{
System.out.println("Enter coefficent for position " + i);
this.coefficient[i] = key.nextInt();
evaluation = Math.pow(value, i)*this.coefficient[0] ;
this.sum += evaluation;
}
return sum;
}
/** Standard toString method */
//needed something better than this below...needed an actual polynomial printed out
public String toString()
{
return "The degree of the polynomial is " + degree + " and the value for which it has been evaluated is" + value;
}
}
This should be along the lines you should be proceeding. I included the main function in your Polynomial class for simplicity, so you will have to modify that if you want to keep it in your tester class. Notice that degree has been made into an integer array of size degree +1(allocated in the constructor):
import java.util.Scanner;
public class Polynomial {
private int degree;
private int [] coefficient;
private double evaluation;
private double sum;
Scanner key = new Scanner(System.in);
public Polynomial(int degree)
{
this.degree = degree;
coefficient = new int [degree+1];
}
public void setCoefficient(int coefficient, int degree)
{
this.coefficient[degree] = coefficient;
}
public int getCoefficient(int degree)
{
return coefficient[degree];
}
public void Evaluate(double value)
{
for (int i=0; i<=degree; i++)
{
System.out.println("Enter coefficent for position " + i);
this.coefficient[i] = key.nextInt();
evaluation = Math.pow(value, i)*this.coefficient[0] ;
this.sum += evaluation;
}
}
public double getSum(){
return sum;
}
public String toString()
{
String s = "";
for (int i=0; i <= degree; i++)
{
s += coefficient[i];
switch (i) {
case 0:
s += " + ";
break;
case 1:
s += "x + ";
break;
default:
s += "x^" + i + ((i==degree)?"":" + ");
}
}
return s;
}
public static void main(String[] args) {
int degree;
double sum;
int coefficient;
Scanner key = new Scanner(System.in);
System.out.println("Enter the degree of the polynomial");
degree=key.nextInt();
Polynomial fun = new Polynomial(degree);
fun.Evaluate(3.0);
System.out.println(" The sum of the polynomial is " + fun.getSum());
System.out.println(fun);
}
}
The usual way of making the objects of a class printable is to supply a toString method in the class, which specifies how to express objects of that class as a String. Methods such as println and other ways of outputting a value will call a class's toString method if they need to print an object of that class.
You should adopt the same pattern with your Polynomial class - write a toString method with all the output logic. Then in your PolynomialTester class, all you need to write is System.out.println(fun); and the rest will just happen. You'll find this far more versatile than writing a method that actually does the printing. For example, you'll be able to write something like
System.out.println("My polynomial is " + fun + " and " + fun + " is my polynomial.");
if that's your idea of fun.
A few other things concern me about your class.
You seem to be only storing one coefficient and one exponent. I'd expect a polynomial to have a whole array of coefficients.
You have fields for evaluation and sum - but these only really make sense while a polynomial is being evaluated. They're not long-term properties of the polynomial. So don't store them in fields. Have them as local variables of the evaluate method, and return the result of the evaluation.
I'd expect a class like this to be immutable. That is, you should provide all the coefficients when the object is created, and just never change them thereafter. If you do it that way, there's no need to write setter methods.
So I've written my own version of your class, that fixes those issues listed above, and implements a toString method that you can use for printing it. A second version of toString lets you specify which letter you want to use for x. I've used "varargs" in the constructor, so you can construct your polynomial with a line such as
Polynomial fun = new Polynomial (7, 2, 5, 0, 1);
specifying the coefficients from the constant term through in order to the coefficient of the term with the highest exponent. Or you can just pass an array.
See that I've changed the logic a wee bit - my version prints the polynomial in the conventional order, from highest to lowest exponent. It leaves off the decimals if the coefficient is an integer. It doesn't print a 1 in front of an x. And it deals cleanly with - signs.
import java.util.Arrays;
public class Polynomial {
private double[] coefficients;
public Polynomial(double... coefficients) {
this.coefficients = Arrays.copyOf(coefficients, coefficients.length);
}
public int getDegree() {
int biggestExponent = coefficients.length - 1;
while(biggestExponent > 0 && coefficients[biggestExponent] == 0.0) {
biggestExponent--;
}
return biggestExponent;
}
public double getCoefficient(int exponent) {
if (exponent < 0 || exponent > getDegree()) {
return 0.0;
} else {
return coefficients[exponent];
}
}
public double evaluateAt(double x) {
double toReturn = 0.0;
for (int term = 0; term < coefficients.length; term++) {
toReturn += coefficients[term] * Math.pow(x, term);
}
return toReturn;
}
#Override
public String toString() {
return toString('x');
}
public String toString(char variable) {
boolean anythingAppendedYet = false;
StringBuilder toReturn = new StringBuilder();
for (int exponent = coefficients.length - 1; exponent >= 0; exponent--) {
if (coefficients[exponent] != 0.0) {
appendSign(toReturn, exponent, anythingAppendedYet);
appendNumberPart(toReturn, exponent);
appendLetterAndExponent(toReturn, exponent, variable);
anythingAppendedYet = true;
}
}
if (anythingAppendedYet) {
return toReturn.toString();
} else {
return "0";
}
}
private void appendSign(StringBuilder toAppendTo, int exponent, boolean anythingAppendedYet) {
if (coefficients[exponent] < 0) {
toAppendTo.append(" - ");
} else if (anythingAppendedYet) {
toAppendTo.append(" + ");
}
}
private void appendNumberPart(StringBuilder toAppendTo, int exponent) {
double numberPart = Math.abs(coefficients[exponent]);
if (numberPart != 1.0 || exponent == 0) {
//Don't print 1 in front of the letter, but do print 1 if it's the constant term.
if (numberPart == Math.rint(numberPart)) {
// Coefficient is an integer, so don't show decimals
toAppendTo.append((long) numberPart);
} else {
toAppendTo.append(numberPart);
}
}
}
private void appendLetterAndExponent(StringBuilder toAppendTo, int exponent, char variable) {
if (exponent > 0) {
toAppendTo.append(variable);
}
if (exponent > 1) {
toAppendTo.append("^");
toAppendTo.append(exponent);
}
}
}
So I tested it with this class
public class PolynomialTester {
public static void main(String[] args) {
Polynomial fun = new Polynomial (7, 2, 5, 0, 1);
System.out.println(fun.getDegree());
System.out.println(fun.evaluateAt(3));
System.out.println(fun);
}
}
and the output was
4
139.0
x^4 + 5x^2 + 2x + 7
then I realised that you wanted to be able to input the coefficients in a loop. So I changed PolynomialTester to this. See how I build the array and then create the object.
import java.util.Scanner;
public class PolynomialTester {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the degree:");
int degree = input.nextInt();
double[] coefficients = new double[degree + 1];
for( int exponent = 0; exponent <= degree; exponent++) {
System.out.println("Enter the coefficient of x^" + exponent);
coefficients[exponent] = input.nextDouble();
}
Polynomial fun = new Polynomial (coefficients);
System.out.println(fun.evaluateAt(3));
System.out.println(fun);
input.close();
}
}
Note that if you really want your polynomial to be printed in "reverse" order, with the constant term first, you could change the loop in the toString method to this.
for (int exponent = 0; exponent < coefficients.length; exponent++) {
You may add a class member String poly, then modify the following method.
public void Evaluate(double value)
{
for (int i=0; i<=degree; i++)
{
System.out.println("Enter coefficent for position " + i);
this.coefficient= key.nextInt();
evaluation = Math.pow(value, i)*coefficient ;
this.sum += evaluation;
this.poly = "";
if(coefficient != 0)
{
if(i > 0)
{
this.poly += " + " + Integer.toString(coefficient) + "x^" + Integer.toString(i); // you may replace x with the actual value if you want
}
else
{
this.poly = Integer.toString(coefficient)
}
}
}
}

How to make the median in java

What am I doing wrong?
The median is always -0.5 result or 0.5, if ((m) + (m+1))/2;
public static double mediana(List<Double> liczby ){
Collections.sort(liczby);
int n = liczby.size()/2;
double m;
m = get(n);
if (liczby.size() % 2 == 0){
return ((m) + (m-1))/2;
}
else {
return m;
}
}
In your code, the problem is in this line.
return ((m) + (m-1))/2;
It should return the average of nth number and (n-1)th number as n = (size of the list)/2. You can try this.
public static double mediana(List<Double> liczby ){
Collections.sort(liczby);
int n = liczby.size()/2;
double m;
if (liczby.size() % 2 == 0)
m = (liczby.get(n) + liczby.get(n-1))/2;
else
m = liczby.get(n);
return m;
}
I believe the problem with it is the line return ((m) + (m-1))/2; You forget to retrieve the input of the next element in the list. Try:
l = get(n+1);
return (m + l)/2;
instead of:
return ((m) + (m-1))/2;
You need to be retrieving the n and n-1-th elements. You are currently subtracting 1 from the n-th value, which is not meaningful:
return (get(n) + get(n-1)) / 2;
I faced the same problem yesterday and I wrote a solution similar to sifho's one.
My method---implemented using Java generics---calculates the median value on every collection of Numbers. You can use the method with collections of Doubles, Integers, Floats and returns a double. Please consider that my method creates another collection in order to not alter the original one.
I provide also a test, have fun. ;-)
public static <T extends Number & Comparable<T>> double median(Collection<T> numbers){
if(numbers.isEmpty()){
throw new IllegalArgumentException("Cannot compute median on empty array of numbers");
}
List<T> numbersList = new ArrayList<>(numbers);
Collections.sort(numbersList);
int middle = numbersList.size()/2;
if(numbersList.size() % 2 == 0){
return 0.5 * (numbersList.get(middle).doubleValue() + numbersList.get(middle-1).doubleValue());
} else {
return numbersList.get(middle).doubleValue();
}
}
JUnit test code snippet:
/**
* Test of median method, of class Utils.
*/
#Test
public void testMedian() {
System.out.println("median");
Double expResult = 3.0;
Double result = Utils.median(Arrays.asList(3.0,2.0,1.0,9.0,13.0));
assertEquals(expResult, result);
expResult = 3.5;
result = Utils.median(Arrays.asList(3.0,2.0,1.0,9.0,4.0,13.0));
assertEquals(expResult, result);
}
Usage example (consider the class name is Utils):
List<Integer> intValues = ... //omitted init
Set<Float> floatValues = ... //omitted init
.....
double intListMedian = Utils.median(intValues);
double floatSetMedian = Utils.median(floatValues);
I do not know how to look method get(n).
It generates automatically.
The method can not return to zero.
private static double get(int n) {
// TODO Auto-generated method stub
return 0;
}

having an issue converting fractions to double

For some reason I've been unable to print a fraction as a double. I can't get past it. It gives formatting errors every time. The parts giving me issues are commented. Class and driver code are below. and help is appreciated.
Class code
public class Fraction1
{
private int numerator;
private int denominator;
public void Fraction1(int n, int d)
{
this.numerator = n;
this.denominator = d;
}
public void print()
{
System.out.println(numerator + "/" + denominator);
}
public Fraction1 add(Fraction1 other)
{
int n = this.numerator * other.denominator +
this.denominator * other.numerator;
int d = this.denominator * other.denominator;
return this;
}
//public void printAsDouble()
//{
// this.printAsDouble();
// System.out.println((double)(numerator)/(double) (denominator));
//}
}
Driver code
import java.util.*;
public class FractionDriver1
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
Fraction c, d, x;
x = new Fraction();
System.out.println("Enter numerator; then denominator.");
c = new Fraction(input.nextInt(), input.nextInt());
c.print();
System.out.println();
System.out.println("Enter numerator; then denominator.");
d = new Fraction(input.nextInt(), input.nextInt());
d.print();
System.out.println("Sum:");
x.add(c).add(d);
x.print();
//x.printAsDouble();
}
}
Should be:
(double)((numerator)/(denominator))
public class Fraction1
{
private int numerator;
private int denominator;
//no return type in constructor
public Fraction1(int n, int d)
{
this.numerator = n;
this.denominator = d;
}
public void print()
{
System.out.println(numerator + "/" + denominator);
}
public Fraction1 add(Fraction1 other)
{
//Does nothing. What does saving the values in n and d give you.
//Nothing. Hence your objects numerator and denominator
//remains 0 and hence 0/0 gives your error
int n = this.numerator * other.denominator +
this.denominator * other.numerator;
int d = this.denominator * other.denominator;
return this;
}
//public void printAsDouble()
//{
// this.printAsDouble();
// System.out.println((double)(numerator)/(double) (denominator));
//}
}
x.add(c).add(d);
So x is an empty object i.e numerator and denominator = 0.
I use the add function, but it does not modify my x object and it remains the same. In the end, i call print and it should always print 0/0.
As per the error you are getting, check your command line arguments, they must be wrong.

I am having problems with compareTo

Well, I need to make a project where I have two interfaces and they are both used in two unrelated classes. I managed to get everything else to work out properly except for the compareTo method. The two classes I have made are Car and Horse. What I am trying to do is compare the milesGoal from Horse to the one in Car and return either a 1, 0, or -1.
However when I try doing this I get the error "double could not be dereferenced"
I have been stuck on this for a while trying to find different ways to approach this part of the code. I tried using compareTo in the tester class instead of making a method but I got the same error and I am required to make it into a method.
This is the Horse Class:
public class Horse implements milesInterface , kilometersInterface{
private double currentMile;
private double currentKilo;
private double milesGoal;
private double kilosGoal;
private String horseBreed;
// CONSTRUCTORS
public Horse(){
currentMile = 0;
currentKilo = 0;
milesGoal = 0;
kilosGoal = 0;
horseBreed = "Unspecified";
}
public Horse(double cm, double ck, double mg, double kg, String hb){
currentMile = cm;
currentKilo = ck;
milesGoal = mg;
kilosGoal = kg;
horseBreed = hb;
}
// MILE METHODS
public double remainingMiles(){ // Finds the remaining miles
return milesGoal-currentMile;
}
public void halfMile(){ // Divides the desired goal halfway (Miles)
milesGoal = milesGoal/2;
}
public void setMileGoal(double newMile){ // Allows you to set a new goal
milesGoal = newMile;
}
public double getMileGoal(){
return milesGoal;
}
// KILOMETER METHODS
public double remainingKilos(){ // Finds the remaining Kilos
return kilosGoal-currentKilo;
}
public void halfKilo(){ // Divides the desire goal halfway (Kilos)
kilosGoal = kilosGoal/2;
}
public void setKiloGoal(){ // Allows you to set a new goal
kilosGoal = milesGoal*1.6;
}
public void setCurrentKilo(){ // Allows you to set the current Kilo
currentKilo = currentMile * 1.6;
}
// UNIQUE METHODS
public double getMilesStatus(){
return currentMile;
}
public double getKilosStatus(){
return currentKilo;
}
public String getHorseBreed(){
return horseBreed;
}
public void convertToKilos(){ // Converts current miles to kilometers
double kilos = currentMile * 1.6;
System.out.println("The current miles to kilometers is: " + kilos + "km.");
}
public void convertToMiles(){ // Converts current kilometers to miles
double miles = currentKilo * .6;
System.out.println("The current kilometers to miles is: " + miles + "m.");
}
public void milesPerHour(double hours){ // Calculates the mph to the goal by a time
double answer = milesGoal / hours;
System.out.println("The mph needed to reach the desination in " + hours + " hours: " + answer);
}
public void kilosPerHour(double hours){ // Calculates the kmph to the goal by a time
double answer = kilosGoal / hours;
System.out.println("The kilometers needed to reach the desination in " + hours + " hours: " + answer);
}
public int compareTo(Object Other){
if(milesGoal > (Horse)milesGoal.Other)
return 1;
if(milesGoal < (Horse)milesGoal.Other)
return 0;
return -1;
}
}
The Car class is pretty much the same as the Horse one and I need to find a way to compare both of their milesGoal to see which one is greater. I tried multiple things but it doesn't seem to work
This is the interface I made:
abstract interface milesInterface{
public double remainingMiles();
public void halfMile();
public void setMileGoal(double newMile);
public int compareTo(Object Other);
}
abstract interface kilometersInterface{
public double remainingKilos();
public void halfKilo();
public void setCurrentKilo();
public int compareTo(Object Other);
}
First, you are writting attribute.object. This is what fails. Other.milesGoal is a better option.
Another problema is with the casting. What you are doing is trying to cast milesGoal.other to Horse (you want to cast milesGoal)
You should use
if (milesGoal > ((Horse) other).milesGoal)
Also, use proper capitalization (variables go in lowercase, clases/interfaces in uppercase) and setters and getters.
Additionally, you probably will want to cast to the interface so you can use the methods with other clases that implement it
if (milesGoal > ((MilesInterface) other).milesGoal)
Firstly, (Horse)milesGoal.Other should be ((Horse) Other).milesGoal.
I would suggest overloading compareTo with one method for comparing to Horses and one method for comparing to Cars. Then your code looks like
public int compareTo(Horse horse){
if(milesGoal > horse.milesGoal)
return 1;
if(milesGoal < horse.milesGoal)
return -1;
return 0;
}
public int compareTo(Car car){
if(milesGoal > car.milesGoal)
return 1;
if(milesGoal < car.milesGoal)
return -1;
return 0;
}

Categories

Resources