Spaces:
Running
Running
| Once upon a time there was a fishing competition. | |
| In the category 'FishMeasurements', the minimum and maximum length and weight of fish allowed in the competition are defined as category variables. | |
| The 'Fish' class models a single fish. | |
| The class has attributes length and weight. | |
| For the Fish class, write the public method | |
| public boolean allowed() | |
| which returns true or false depending on whether the given Fish object is within the allowed limits in a competition. | |
| import java.util.Random; | |
| public class Test{ | |
| public static void main(String[] args){ | |
| final Random rnd = new Random(); | |
| System.out.println("Testing the method allowed..."); | |
| for (int i=0; i<10; i++){ | |
| Fish fish = new Fish(rnd.nextInt(80) + 10, rnd.nextInt(7) + rnd.nextDouble()); | |
| System.out.println("" + fish); | |
| System.out.println(fish.allowed() ? "Allowed" : "Not allowed"); | |
| } | |
| } | |
| } | |
| class FishMeasurements{ | |
| public static final int MINIMUM_LENGTH = 25; | |
| public static final int MAXIMUM_LENGTH = 75; | |
| public static final double MINIMUM_WEIGHT = 1.0; | |
| public static final double MAXIMUM_WEIGHT = 5.0; | |
| } | |
| class Fish{ | |
| private int length; | |
| private double weight; | |
| public Fish(int length, double weight){ | |
| this.length = length; | |
| this.weight = weight; | |
| } | |
| // ADD | |
| public boolean allowed() { | |
| boolean allowed = false; | |
| if (this.length >= FishMeasurements.MINIMUM_LENGTH && | |
| this.length <= FishMeasurements.MAXIMUM_LENGTH && | |
| this.weight >= FishMeasurements.MINIMUM_WEIGHT && | |
| this.weight <= FishMeasurements.MAXIMUM_WEIGHT) { | |
| allowed = true; | |
| } | |
| return allowed; | |
| } | |
| public String toString(){ | |
| return "Length:" + length + ", weight:" + weight; | |
| } | |
| } | |
| Testing the method allowed... | |
| Length:22, weight:1.692058179594544 | |
| Not allowed | |
| Length:26, weight:0.5860256329845314 | |
| Not allowed | |
| Length:85, weight:3.3517439256862196 | |
| Not allowed | |
| Length:33, weight:3.5979307720496427 | |
| Allowed | |
| Length:77, weight:5.786405319523382 | |
| Not allowed | |
| Length:35, weight:2.368043874796682 | |
| Allowed | |
| Length:58, weight:4.67477898551802 | |
| Allowed | |
| Length:50, weight:5.1839866609623915 | |
| Not allowed | |
| Length:44, weight:3.8234901017754215 | |
| Allowed | |
| Length:12, weight:1.6789547620765946 | |
| Not allowed | |