Here is the task:
Create several classes of flowers that extend abstract flower. all fields -- random.
- make a bunch of 20 different flowers
- calculate the price of the bunch
- sort bunch by freshness of flowers
- find flowers with stalks in a certain range
- find average level of freshness of the bunch
Solution:
public abstract class Flower implements Comparable<Flower> {
public String name;
public double freshness;
public double stalk;
public double price;
public Flower(String name) {
super();
Random rand = new Random();
this.name = name;
this.freshness = rand.nextDouble() * 100;
this.stalk = rand.nextDouble() * 150 + 30;
this.price = rand.nextDouble() * 1000 + 1;
}
// getters and setters
@Override
public int compareTo(Flower that) {
return (int) (that.getFreshness() - this.getFreshness());
}
@Override
public String toString() {
return this.name + " " + this.freshness + "\n";
}
Every class of a particular flower looks like this:
public class Rose extends Flower {
public Rose() {
super("rose");
}
}
Main method:
public class Main {
public static List<Flower> flowers = new ArrayList<Flower>();
public static List<Flower> bunch = new ArrayList<Flower>();
public static Random random = new Random();
public static double bunchPrice;
public static double stalkMin = 30;
public static double stalkMax = 100;
public static void main(String[] args) {
flowers.add(new Rose());
flowers.add(new Orchid());
flowers.add(new Gerbera());
flowers.add(new Daisy());
for (int i = 0; i < 20; i++) {
bunch.add(flowers.get(random.nextInt(flowers.size())));
bunchPrice = bunchPrice + bunch.get(i).getPrice();
}
System.out.println("the bunch ====================");
System.out.println(bunch);
System.out.println("\nprice of the bunch ====================");
System.out.println(bunchPrice);
System.out.println("\nflowers sorted by price ====================");
Collections.sort(bunch);
System.out.println(bunch);
System.out.println("\nflowers with stalks in range from " + stalkMin + " to " + stalkMax + "====================");
for(Flower f: bunch) {
if(f.getStalk() > stalkMin && f.getStalk() < stalkMax){
System.out.println(f.getName() + " " + f.getStalk());
}
}
System.out.println("\naverage level of freshness in the bunch ====================");
double sumFreshness = 0;
for(Flower f: bunch) {
sumFreshness = sumFreshness + f.getFreshness();
}
System.out.println(sumFreshness/ bunch.size());
}
}
Control-K
for faster indenting. \$\endgroup\$