In: Computer Science
Complete class Cow so that it has:
(a) an int attribute to hold a number of legs,
(b) a constructor that takes one parameter, a number of legs (c) a
getter method for the attribute
(d) a method to convert any instance of Cow to a string
class Cow{ ____________________________________ ____________________________________ Cow(________________________){ ____________________________________ ____________________________________ } ____ getNumLegs(){ ____________________________________ ____________________________________ } ____________________________________ ____________________________________ ____________________________________ ____________________________________ ____________________________________
}
public class MinOfSet {
/** * Write a method (use the code provided) that takes
* a collection of Cows and * returns the Cow that has the minimum number of legs. * Assume the collection contains at least one cow. */ public static Cow minCow(Collection<Cow> herd){
Cow answer = null; Iterator<Cow> icow = herd.iterator();
____________________________________ ____________________________________ ____________________________________ ____________________________________ ____________________________________ ____________________________________ ____________________________________ ____________________________________
}
public static void main(String[] args) {
//Put two cows in the herd and then print the cow with minimum legs Collection<Cow> herd = new HashSet<>(); ____________________________________ ____________________________________ ____________________________________ ____________________________________
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
class Cow {
private int numLegs;
//constructor
public Cow(int aNumLegs) {
super();
numLegs = aNumLegs;
}
//getter
public int getNumLegs() {
return numLegs;
}
//tostring
public String toString() {
return "Cow [Num of Legs : " +
numLegs + "]";
}
}
public class MinOfSet {
public static Cow minCow(Collection<Cow> herd)
{
Cow answer = null;
Iterator<Cow> icow =
herd.iterator();
Cow temp = null;
answer = icow.next();
//iterating objects from set
while (icow.hasNext()) {
//checking if
cow has less legs than other
// if yes
swap
temp =
icow.next();
if
(temp.getNumLegs() < answer.getNumLegs())
answer = temp;
}
return answer;
}
public static void main(String[] args) {
Collection<Cow> herd = new
HashSet<>();
//creating and adding cow object to
hasset
herd.add(new Cow(3));
herd.add(new Cow(4));
System.out.println(minCow(herd));
}
}
Note : If you like my answer please rate and help me it is very Imp for me