its having 2 issues 1) compareTo method is incorrect (A method named compareTo which returns a positive int, a negative int, or zero depending on order of this object and the otherMoney argument. ) 2) 2 of the values (highlighted) are ordered incorrectly see the picture
I have the following code:
public class Money {
private int dollar;
private int cent;
final static int MIN_CENT_VALUE = 0;
final static int MAX_CENT_VALUE = 99;
public Money() {
this.dollar = 0;
this.cent = 0;
}
public Money(int dollar, int cent) {
this.dollar = dollar;
if (cent >= MIN_CENT_VALUE && cent <= MAX_CENT_VALUE) {
this.cent = cent;
} else {
cent = 0;
}
}
public int getDollar() {
return this.dollar;
}
public void setDollar(int dol) {
this.dollar = dol;
}
public int getCent() {
return this.cent;
}
public void setCent(int c) {
if (c >= MIN_CENT_VALUE && c <= MAX_CENT_VALUE) {
this.cent = c;
}
}
public Money add(Money otherMoney) {
Money m = new Money();
m.dollar = dollar + otherMoney.dollar;
m.cent = cent + otherMoney.cent;
if (m.cent >= 100) {
m.dollar++;
m.cent -= 100;
}
return m;
}
public Money subtract(Money otherMoney) {
Money m = new Money();
m.dollar = dollar - otherMoney.dollar;
m.cent = cent - otherMoney.cent;
if (m.dollar < 0 || m.cent < 0) {
return null;
}
return m;
}
public boolean equals(Money otherMoney) {
return this == otherMoney;
}
public int compareTo(Money otherMoney) {
if (this.dollar < otherMoney.dollar) {
return this.dollar - otherMoney.dollar;
} else if (this.dollar == otherMoney.dollar) {
return 0;
} else {
return this.dollar- otherMoney.dollar;
}
}
public String toString() {
if (this.cent<10){
return "$" + this.dollar + ".0" + this.cent;
}
return "$" + this.dollar + "." + this.cent;
}
public static Money max(Money[] m) {
int max = m[0].dollar;
int index = 0;
for (int i = 0; i < m.length; i++) {
if (max < m[i].dollar) {
max = m[i].dollar;
index = i;
}
}
return m[index];
}
public static void selectionSort(Money arr[]) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int min = i;
for (int j = i + 1; j < n; j++)
if (arr[j].dollar < arr[min].dollar)
min = j;
// Swap the found minimum element with the first element
Money temp = new Money();
temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
}
public static void printList(Money[] m, int i) // This method takes an array of object as parameter
{
for (Money mm : m){
System.out.print(mm + " ");
}
System.out.println();
}
}
its having 2 issues
1) compareTo method is incorrect (A method named compareTo which returns a positive int, a negative int, or zero
depending on order of this object and the otherMoney argument. )
2) 2 of the values (highlighted) are ordered incorrectly
see the picture
Step by step
Solved in 2 steps