Help, I need some revision on this code. How do I get the values of 65 and 106 without removing it from Exercise3 myExer3 = new Exercise3(65,106);
Base Class:
public class Exercise3 {
private int Voltage;
private int Resistance;
public void setVoltage(int temp){
if (Voltage == 65)
Voltage = temp;
}
public void setResistance(int temp){
if (Resistance == 106 )
Resistance =106;
}
public int getVoltage (){
return (Voltage);
}
public int getResistance(){
return(Resistance);
}
}
Test Class:
public class Test_Excercise3 {
public static void main(String []args){
Exercise3 myExer3 = new Exercise3(65,106);
System.out.println("Voltage: "+myExer3.getVoltage());
System.out.println("Resistance: "+myExer3.getResistance());
System.out.println("Current : "+ (myExer3.getVoltage()/myExer3.getResistance()));
}
}
So that I could get the result of 0.61 Ohm's or the Current.
Your class needs a constructor:
public class Exercise3 {
private int voltage;
private int resistance;
public Exercise3(int voltage, int resistance) {
this.voltage = voltage;
this.resistance = resistance;
}
...
}
For more information, consult the Java Tutorials on providing constructors for your classes.
Add a constructor to the Excercise3 and correct setters, also do conversion to (double) of the result.
public class JavaApplication27
{
public static class Exercise3
{
private int voltage;
private int resistance;
public void setVoltage(int v)
{
voltage = v;
}
public void setResistance(int res)
{
resistance = res;
}
public int getVoltage()
{
return voltage;
}
public int getResistance()
{
return resistance;
}
public Exercise3(int v, int res)
{
setVoltage(v);
setResistance(res);
}
public double getCurrent() //helper method :)
{
return (double) getVoltage() / getResistance();
}
}
public static void main(String[] args)
{
Exercise3 myExer3 = new Exercise3(65, 106);
System.out.println("Voltage : " + myExer3.getVoltage());
System.out.println("Resistance: " + myExer3.getResistance());
System.out.println("Current : " + ( (double) myExer3.getVoltage() / myExer3.getResistance())); // Since resistance and voltage are int's, the result of int/int division is int. To get a double) result use (double) :).
System.out.println("Current : " + myExer3.getCurrent()); //you may also use helper method to calculate current
System.out.format( "Current : %.2f", myExer3.getCurrent() ); // to get .61 must use formatter
}
}
Output:
Voltage : 65
Resistance: 106
Current : 0.6132075471698113
Current : 0.6132075471698113
Current : 0.61
Related
I wrote my own AtomicDouble class and I also have a BankAccount class that does two simple withdrawals and deposits operations and it has an AtomicDouble instance(balance). The problem with my code is that when I call the addAndGet method in deposit(), the program falls into an infinite loop, and compareAndSet() never returns the true value, but when I debugged this, currentValue and the value from atomic.get () were equal, but this method does not understand.
The interesting thing is that when I put if (atomic.get()==currentValue) instead of if (atomic.compareAndSet(currentValue, nextValue)), the program runs properly.
public class AtomicDouble extends Number {
private final AtomicReference<Double> atomic;
public AtomicDouble() {
this(0.0);
}
public AtomicDouble(double initialValue) {
atomic = new AtomicReference<>(initialValue);
}
public final double addAndGet(double delta) {
while (true) {
double currentValue = atomic.get();
double nextValue = currentValue + delta;
if (atomic.compareAndSet(currentValue, nextValue))
return nextValue;
}
}
public final double incrementAndGet() {
return addAndGet(1);
}
public final void set(double newValue) {
atomic.set(newValue);
}
public final double get() {
return atomic.get();
}
public final double getAndSet(double newValue) {
return atomic.getAndSet(newValue);
}
public float floatValue() {
return (float) get();
}
#Override
public double doubleValue() {
return get();
}
public int intValue() {
return (int) get();
}
public long longValue() {
return (long) get();
}
public String toString() {
return Double.toString(get());
}
}
public class BankAccount {
private final AtomicDouble balance;
private String accountNumber;
public BankAccount(double balance, String accountNumber) {
this.balance = new AtomicDouble(balance);
this.accountNumber = accountNumber;
}
public void deposit(double number, String color) {
System.out.println(color + "deposit " + number + " current balance=" + balance.addAndGet(number));
}
public void withdraw(double number, String color) {
if (this.balance.get() - number >= 0) {
System.out.println(color + "Withdraw " + number + " current balance=" + balance.addAndGet(-number));
return;
}
System.out.println(color + "Not enough balance");
}
public static void main(String[] args) {
BankAccount bankAccount = new BankAccount(1000.0, "4234236");
ExecutorService threadsPool = Executors.newFixedThreadPool(2);
threadsPool.execute(new Runnable() {
#Override
public void run() {
bankAccount.deposit(300.0, ThreadColor.ANSI_YELLOW);
bankAccount.withdraw(50.0, ThreadColor.ANSI_YELLOW);
}
});
threadsPool.execute(new Runnable() {
#Override
public void run() {
bankAccount.deposit(203.75, ThreadColor.ANSI_BLUE);
bankAccount.withdraw(100.0, ThreadColor.ANSI_BLUE);
}
});
threadsPool.shutdown();
}
}
output: There is no output
I would suppose it is because of autoboxing. You can't have a reference to double, you have a reference to Double.
The operands get "reboxed" each time around the loop and therefore references are never identical. That is, the reference in currentValue is never the same as the reference in atomic.
Try using currentValue reference types.
public final double addAndGet(double delta) {
while (true) {
Double currentValue = atomic.get();
Double nextValue = currentValue + delta;
if (atomic.compareAndSet(currentValue, nextValue))
return nextValue;
}
}
(Fortunately, Double is an immutable type, otherwise this would have a race hazard)
So I am currently learning about interfaces within java and in this program I created 3 separate classes Building.class, Bicycle.class, and Car.class and they are unrelated but they all use the CarbonFootPrint Interface. in my processCarbonFootPrintData class I created an arrayList that holds the data from my objects then I loop through the array list and I get this weird output that does not show the result of my input data.
package CarbonFootPrintPackage;
import java.util.Scanner;
/**
*
* #author cjt1496
*/
public class Building implements CarbonFootPrintInterface {
private int numberOfFloors;
private int numberOfJanitors;
private boolean isBuildingOpenOrClosed;
double naturalGasConsumed;
Scanner input = new Scanner(System.in);
public double getNaturalGasConsumed() {
return naturalGasConsumed;
}
public void setNaturalGasConsumed(double naturalGasConsumed) {
this.naturalGasConsumed = naturalGasConsumed;
}
public int getNumberOfFloors() {
return numberOfFloors;
}
public void setNumberOfFloors(int numberOfFloors) {
this.numberOfFloors = numberOfFloors;
}
public int getNumberOfJanitors() {
return numberOfJanitors;
}
public void setNumberOfJanitors(int numberOfJanitors) {
this.numberOfJanitors = numberOfJanitors;
}
public boolean isIsBuildingOpenOrClosed() {
return isBuildingOpenOrClosed;
}
public void setIsBuildingOpenOrClosed(boolean isBuildingOpenOrClosed) {
this.isBuildingOpenOrClosed = isBuildingOpenOrClosed;
}
public Building(){
}
public Building(int numberOfFloors, int numberOfJanitors, boolean isBuildingOpenOrClosed, double naturalGasConsumed) {
this.numberOfFloors = numberOfFloors;
this.numberOfJanitors = numberOfJanitors;
this.isBuildingOpenOrClosed = isBuildingOpenOrClosed;
this.naturalGasConsumed = naturalGasConsumed;
}
public void calculateCarbonFootPrint(){
System.out.println("Now Calculating Carbon foot print for a Building ");
System.out.println("--------------------------------------------------------");
System.out.println("How many therms of natural gas has your building consumed?");
naturalGasConsumed = input.nextDouble();
}
#Override
public void getCarbonFootPrint() {
System.out.println("The carbon foot print emitted from this building is " +
(getNaturalGasConsumed() * 11.7) + "pounds of CO2 from natural gas use.\n");
}
}
START OF CAR.CLASS
public class Car implements CarbonFootPrintInterface {
private int numberOfSeats;
private int steeringWheel;
double emissionConversionFactor;
double distanceTraveled;
int numberOfTimesTraveled;
Scanner input = new Scanner(System.in);
public int getNumberOfSeats() {
return numberOfSeats;
}
public void setNumberOfSeats(int numberOfSeats) {
this.numberOfSeats = numberOfSeats;
}
public int getSteeringWheel() {
return steeringWheel;
}
public void setSteeringWheel(int steeringWheel) {
this.steeringWheel = steeringWheel;
}
public double getEmissionConversionFactor() {
return emissionConversionFactor;
}
public void setEmissionConversionFactor(double emissionConversionFactor) {
this.emissionConversionFactor = emissionConversionFactor;
}
public double getDistanceTraveled() {
return distanceTraveled;
}
public void setDistanceTraveled(double distanceTraveled) {
this.distanceTraveled = distanceTraveled;
}
public int getNumberOfTimesTraveled() {
return numberOfTimesTraveled;
}
public void setNumberOfTimesTraveled(int numberOfTimesTraveled) {
this.numberOfTimesTraveled = numberOfTimesTraveled;
}
public Car(){
}
public Car(int numberOfSeats, int steeringWheel, double emissionConversionFactor, double distanceTraveled, int numberOfTimesTraveled) {
this.numberOfSeats = numberOfSeats;
this.steeringWheel = steeringWheel;
this.emissionConversionFactor = emissionConversionFactor;
this.distanceTraveled = distanceTraveled;
this.numberOfTimesTraveled = numberOfTimesTraveled;
}
public void calculateCarbonFootPrint(){
System.out.println("Now Calculating Carbon foot print for a Car ");
System.out.println("--------------------------------------------------------");
System.out.println("Enter your emissionConversionFactor (Must be a decimal)");
emissionConversionFactor = input.nextDouble();
System.out.println("Enter your distance traveled in km (Must be a decimal)");
distanceTraveled = input.nextDouble();
System.out.println("Enter the number of times you traveled to your destination");
numberOfTimesTraveled = input.nextInt();
}
#Override
public void getCarbonFootPrint() {
System.out.println("The carbon foot print emitted from this bicycle is " +
getEmissionConversionFactor() * (getDistanceTraveled() * getNumberOfTimesTraveled()) +"Kg CO2e\n");
}
}
START OF BICYCLE.CLASS
import java.util.Scanner;
public class Bicycle implements CarbonFootPrintInterface {
private int handleBars;
private boolean KickStand;
double emissionConversionFactor;
double distanceTraveled;
int numberOfTimesTraveled;
Scanner input = new Scanner(System.in);
public int getHandleBars() {
return handleBars;
}
public void setHandleBars(int handleBars) {
this.handleBars = handleBars;
}
public boolean isKickStand() {
return KickStand;
}
public void setKickStand(boolean KickStand) {
this.KickStand = KickStand;
}
public double getEmissionConversionFactor() {
return emissionConversionFactor;
}
public void setEmissionConversionFactor(double emissionConversionFactor) {
this.emissionConversionFactor = emissionConversionFactor;
}
public double getDistanceTraveled() {
return distanceTraveled;
}
public void setDistanceTraveled(double distanceTraveled) {
this.distanceTraveled = distanceTraveled;
}
public int getNumberOfTimesTraveled() {
return numberOfTimesTraveled;
}
public void setNumberOfTimesTraveled(int numberOfTimesTraveled) {
this.numberOfTimesTraveled = numberOfTimesTraveled;
}
public Bicycle(){
}
public Bicycle(int handleBars, boolean KickStand, double emissionConversionFactor, double distanceTraveled, int numberOfTimesTraveled) {
this.handleBars = handleBars;
this.KickStand = KickStand;
this.emissionConversionFactor = emissionConversionFactor;
this.distanceTraveled = distanceTraveled;
this.numberOfTimesTraveled = numberOfTimesTraveled;
}
public void calculateCarbonFootPrint(){
System.out.println("Now Calculating Carbon foot print for Bicycle ");
System.out.println("--------------------------------------------------------");
System.out.println("Enter your emissionConversionFactor (Must be a decimal)");
emissionConversionFactor = input.nextDouble();
System.out.println("Enter your distance traveled in km (Must be a decimal)");
distanceTraveled = input.nextDouble();
System.out.println("Enter the number of times you traveled to your destination");
numberOfTimesTraveled = input.nextInt();
}
#Override
public void getCarbonFootPrint() {
System.out.println("The carbon foot print emitted from this bicycle is " +
getEmissionConversionFactor() * (getDistanceTraveled() * getNumberOfTimesTraveled()) +"Kg CO2e\n");
}
START Of PROCESS_CARBON_FOOTPRINT_DATA CLASS
public class ProcessCarbonFootPrintData {
public void createCarbonFootPrint(){
Building newBuilding = new Building();
Car newCar = new Car();
Bicycle newBicycle = new Bicycle();
newBuilding.calculateCarbonFootPrint();
newCar.calculateCarbonFootPrint();
newBicycle.calculateCarbonFootPrint();
ArrayList footPrint = new ArrayList();
footPrint.add(newBuilding);
footPrint.add(newCar);
footPrint.add(newBicycle);
for (Object footPrint1 : footPrint) {
System.out.println(footPrint1.toString());
}
}
}
This is the output I am getting:
CarbonFootPrintPackage.Building#42a57993
CarbonFootPrintPackage.Car#75b84c92
CarbonFootPrintPackage.Bicycle#6bc7c054
ArrayList footPrint = new ArrayList();
footPrint.add(newBuilding);
footPrint.add(newCar);
footPrint.add(newBicycle);
for (Object footPrint1 : footPrint) {
System.out.println(footPrint1.toString());
}
Your arraylist contains Objects, it doesn't know anything further of the type. When you do:
for ( Object footPrint1 : footPrint) {
}
You also declare the elements to be of type Object.
There are two things you need to do:
Be specific about the type. If you want to keep your List as is, with the different types, change your loop to:
for ( Object footPrint1 : footPrint) {
if ( footPrint1 instanceof Car )
System.out.println((Car)footPrint1);
else if ( footPrint1 instanceof Building )
System.out.println((Building)footPrint1);
else System.out.println((Bicycle)footPrint1);
}
This way, it'll know what type of data to print.
By just doing that, you'll still run into the same issue, because you haven't overridden your toString methods.
Add the following to your Car class:
#Override
public String toString() {
return "I am a car!!";
}
and you'll see that for the Car instance, that line is printed, instead of the memory address.
Override that method for all your classes, and alter the value returned by it the way you want it to be.
public class Sales {
public static void main(String[] args) {
int ursales = 6000;
int target = 3000;
if (ursales >= 2 * target) {
System.out.println("performance Excellent");
System.out.println("bouns 1000");
} else if (ursales >= 1.5 * target) {
System.out.println("performance Fine");
System.out.println("bouns 500");
} else if (ursales >= target) {
System.out.println("performance Satisfactory");
System.out.println("bouns 100");
} else {
System.out.println("You Are Fired!");
}
}
}
I tried to write each statement like:
performance = "...";
bonus = "...";
but it didn't work.
Can someone tell me if there is other possible way to write this statements without System.out.println?
Are you ready for verbosity? We define a Bonus interface that determines if a sales hits the target which is defined by implementation. We then create a Stream, which is ordered, and then return the first result in the stream that filter meets. The upside to this approach is that if you want to add more bonuses in the future it's extremely easy to do so.
interface Bonus {
boolean hit(int sales, int target);
}
static class ExcellentBonus implements Bonus {
#Override
public boolean hit(int sales, int target) {
return sales >= target * 2;
}
}
static class FineBonus implements Bonus {
#Override
public boolean hit(int sales, int target) {
return sales >= target * 1.5;
}
}
static class SatisfactoryBonus implements Bonus {
#Override
public boolean hit(int sales, int target) {
return sales >= target;
}
}
static class FiredBonus implements Bonus {
#Override
public boolean hit(int sales, int target) {
return sales < target;
}
}
public static void main(String[] args) {
int sales = 100;
int target = 50;
Bonus bonus = Stream.of(new ExcellentBonus(), new FineBonus(), new SatisfactoryBonus())
.filter(b -> b.hit(sales, target)).findFirst().orElse(new FiredBonus());
}
SOmething like this?
String performance;
int bonus;
if (ursales >= 2 * target) {
performance = "performance Excellent";
bonus = 1000;
} else if (ursales >= 1.5 * target) {
performance = "fine";
bonus = 500;
} else ... etc..
System.out.println("performance " + performance );
System.out.printkn("bouns " + bonus );
Instead of using System.out.println() you can use System.out.print(). This will not create any new lines when printing to the console.
You may use a StringBuilder to concat all the strings you need and print them all at once in the end.
This solution is similar to #Jason's answer, but uses a slightly different contract. It is similar in the way that it defines a class to represent the result of the performance evaluation. It differs in the form that it allows defining a map of factors to performance evaluations.
Ideone demo
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class Main {
public static void main(final String... args) {
final String FORMAT = "Performance %s\nbonus %d";
final Map<Double, PerformanceResult> performanceResultMap = new HashMap<>();
performanceResultMap.put(2.0, new PerformanceResult("Excellent", 1000));
performanceResultMap.put(1.5, new PerformanceResult("Fine", 500));
performanceResultMap.put(1.0, new PerformanceResult("Satisfactory", 100));
final PerformanceResult excellent =
calculatePerformance(200.0, 100.0, performanceResultMap);
System.out.println(String.format(FORMAT, excellent.getMessage(), excellent.getBonus()));
final PerformanceResult fine = calculatePerformance(150.0, 100.0, performanceResultMap);
System.out.println(String.format(FORMAT, fine.getMessage(), fine.getBonus()));
final PerformanceResult satisfactory =
calculatePerformance(100.0, 100.0, performanceResultMap);
System.out.println(String.format(FORMAT, satisfactory.getMessage(), satisfactory.getBonus()));
try {
calculatePerformance(0, 100, performanceResultMap);
throw new IllegalStateException("Exception should have been thrown");
} catch (final NoFittingPerformanceResultFoundException e) {
System.out.println("Expected exception thrown");
}
}
public static PerformanceResult calculatePerformance(
final double actual,
final double target,
final Map<Double, PerformanceResult> performanceResultMap) {
return performanceResultMap.keySet().stream()
.sorted(Collections.reverseOrder())
.filter(factor -> actual >= target * factor)
.findFirst()
.map(performanceResultMap::get)
.orElseThrow(NoFittingPerformanceResultFoundException::new);
}
}
class PerformanceResult {
private final String message;
private final int bonus;
PerformanceResult(final String message, final int bonus) {
this.message = Objects.requireNonNull(message);
this.bonus = bonus;
}
public String getMessage() {
return message;
}
public int getBonus() {
return bonus;
}
}
class NoFittingPerformanceResultFoundException extends IllegalStateException {}
Apologies if this is trivial to most but I just can't figure this issue out!!
I am creating a mock game where I have a start, end, and hops along. There are portals where if you go on a white portal you jump further ahead and there are black ones where you go backwards. I have set up the class as a POJO;
private int totalSize;
private int minDice;
private int maxDice;
private int whitePortalStart;
private int whitePortalEnd;
private int blackPortalStart;
private int blackPortalEnd;
private int startPosition = 1;
private int currentPosition;
public GameObject(){}
public int getTotalSize() {
return totalSize;
}
public void setTotalSize(int totalSize) throws Exception {
if(totalSize <= 0){
throw new Exception("Can't have a total distance of less than or equal to 0");
} else {
this.totalSize = totalSize;
}
}
public int getMinDice() {
return minDice;
}
public void setMinDice(int minDice) throws Exception {
if(minDice <= 0){
throw new Exception("Can't have a min dice value of less than or equal to 0");
} else {
this.minDice = minDice;
}
}
public int getMaxDice() {
return maxDice;
}
public void setMaxDice(int maxDice) throws Exception {
if(getMinDice() > maxDice){
throw new Exception("Cant have minimum dice number greater than the larger dice number");
} else {
this.maxDice = maxDice;
}
}
public int getWhitePortalStart() {
return whitePortalStart;
}
public void setWhitePortalStart(int whitePortalStart) throws Exception {
this.whitePortalStart = whitePortalStart;
}
public int getWhitePortalEnd() {
return whitePortalEnd;
}
public void setWhitePortalEnd(int whitePortalEnd) throws Exception {
this.whitePortalEnd = whitePortalEnd;
}
public int getBlackPortalStart() {
return blackPortalStart;
}
public void setBlackPortalStart(int blackPortalStart) throws Exception {
this.blackPortalStart = blackPortalStart;
}
public int getBlackPortalEnd() {
return blackPortalEnd;
}
public void setBlackPortalEnd(int blackPortalEnd) throws Exception {
this.blackPortalEnd = blackPortalEnd;
}
public GameObject builder(int n) throws Exception {
setTotalSize(n);
return this;
}
public GameObject whitePortal(int m, int o) throws Exception {
setWhitePortalStart(m);
setWhitePortalEnd(o);
return this;
}
public GameObject blackPortal(int o, int m) throws Exception {
setBlackPortalStart(o);
setBlackPortalEnd(m);
return this;
}
public GameObject dice(int i, int j) throws Exception {
setMinDice(i);
setMaxDice(j);
return this;
}
public int rollDice(){
Random random = new Random();
int min = getMinDice();
int max = getMaxDice();
return random.nextInt(max - min + 1) + min;
}
public void build(){
int totalDistance = getTotalSize();
currentPosition = startPosition;
while(currentPosition < totalDistance){
int diceValue = rollDice();
if(currentPosition + diceValue > getTotalSize()){
System.out.println("CurrentPosition : " + (currentPosition + diceValue) + ", is larger than the total size of the road - " + totalSize);
continue;
} else if(currentPosition + diceValue == getWhitePortalStart()){
System.out.println("You landed on a white portal. Advancing from position " + (currentPosition + diceValue) + " to " + getWhitePortalEnd());
currentPosition = getWhitePortalEnd();
} else if(currentPosition + diceValue == getBlackPortalStart()){
System.out.println("You landed on a black portal. Moving from position " + (currentPosition + diceValue) + " to " + getBlackPortalEnd());
currentPosition = getBlackPortalEnd();
} else {
System.out.println("You landed on " + (currentPosition + diceValue));
currentPosition += diceValue;
}
}
}
So in my main method I call the it like create and call this class like;
WorldOfOz oz = new WorldOfOz();
oz.go.builder(30)
.dice(1, 4)
.whitePortal(5, 12)
.blackPortal(13, 2)
.build();
My issue is when I want to add in more than 1 whitePortal/blackPortal
WorldOfOz oz = new WorldOfOz();
oz.go.builder(30)
.dice(1, 4)
.whitePortal(5, 12)
.whitePortal(18, 26)
.blackPortal(13, 2)
.build();
The values 18 - 26 override 5 - 12. How can I set this up so I can have multiple white and black portals?
It seems that your data structure is not enough to solve this problem.
You need to define a collection of whitePortals and a collection of blackPortals. If you do so calling the method whitePortal(5, 12) add a new white portal insted of setting the white portal values of the only white existing portal.
You need to define a class Portal
public class Portal {
private int portalStart;
private int portalEnd;
...
public Portal(int s, int e) {
this.portalStart = s;
this.portalEnd = e;
}
}
Then you can use it in the GameObject as follow:
public GameObject {
List<Portal> whitePortals;
List<Portal> blackPortals;
public GameObject() {
whitePortals = new ArrayList<Portal>();
blackPortals = new ArrayList<Portal>();
}
public GameObject addWhitePortal(int m, int o) throws Exception {
whitePortals.add(new Portal(m, o));
return this;
}
...
// You need to change other methods to follow a different data structure
}
Well, you can use the following approach:
Introduce a new "Portal" type with start/end attributes
Replace white/black portal attributes in your class with lists for white and black portals (or any other type of collection you like)
Replace getWhite/Black methods with access to lists
Refactor whitePortal and blackPortal method to create new instances of a portal object and add them to an appropriate collection
You can, of course, use arrays instead of collections, but that's a bit more cumbersome.
Also, assuming portals are collections, you probably need to add helper methods for operating on those. Depending on what your actual needs are.
public class Portal
{
private int start;
private int end;
public Portal(int start, int end) { ... }
public getStart() {...}
public getEnd() {...}
public setStart(int end) {...}
public setEnd(int start) {...}
}
public class GameObject
{
...
private List<Portal> whitePortals = new ArrayList<Portal>();
private List<Portal> blackPortals = new ArrayList<Portal>();
...
public GameObject whitePortal(int m, int o) throws Exception {
whitePortals.add(new Portal(m, o));
return this;
}
public GameObject blackPortal(int o, int m) throws Exception {
blackPortals.add(new Portal(m, o));
return this;
}
...
}
Im trying to sort my planes by Ascending and Descending order. I have a hashmap of planes and i want to compare them so that i can get the next plane due and last plane due by sorting the map by timeLimitBeforeLand. I wrote a compareTo method which looks like :
//---------------------------------------------------------------------------------------
// CompareTo() used with the Comparable implementation.
//---------------------------------------------------------------------------------------
public int compareTo(Object arg0)
{
if((arg0 != null) && (arg0 instanceof Plane))
{
Plane p = (Plane) arg0;
return (int)Math.ceil(this.timeLimitBeforeLand - p.getLimitBeforeLand());
}
return 0;
}
CompareTo takes timeLimitBeforeLand:
// ---------------------------------------------------------------------------------------
// Name: getTimeLimitBeforeLand.
// Description: Get the time before every plane is going to land.
//---------------------------------------------------------------------------------------
public double getTimeLimitBeforeLand()
{
double fuelConsumption;
double timeLimitBeforeLand = 0;
for (TreeMap<String, Plane> theEntry : airlineMap.values()) {
for (Plane aPlane : theEntry.values()) {
if (aPlane.getPlaneType() == aPlane.getPlaneType().AIRBUS) {
System.out.println(" ");
System.out.println(aPlane);
fuelConsumption = 2;
timeLimitBeforeLand = (double) (aPlane.getFuelRemaining() / fuelConsumption);
System.out.println(timeLimitBeforeLand + " minutes to land.");
System.out.println(" ");
} else if (aPlane.getPlaneType() == aPlane.getPlaneType().CORPORATE) {
System.out.println(" ");
System.out.println(aPlane);
fuelConsumption = 3;
timeLimitBeforeLand = (aPlane.getFuelRemaining() / fuelConsumption);
System.out.println(timeLimitBeforeLand + " minutes to land.");
System.out.println(" ");
} else if (aPlane.getPlaneType() == aPlane.getPlaneType().PRIVATE) {
System.out.println(" ");
System.out.println(aPlane);
fuelConsumption = 4;
timeLimitBeforeLand = (double) (aPlane.getFuelRemaining() / fuelConsumption);
System.out.println(timeLimitBeforeLand + " minutes to land.");
System.out.println(" ");
}
}
}
return timeLimitBeforeLand;
}
My attempt so far in the mainApp:
TreeMap<String, PlaneStore> map = new TreeMap<String, PlaneStore>();
ArrayList<Plane> copyList = new ArrayList<Plane>(map.);
Plane comp = new Plane();
Collections.sort(copyList, plane);
Plane Class:
//---------------------------------------------------------------------------------------
// Name: Imports.
// Description: To allow the use of different Java classes.
//---------------------------------------------------------------------------------------
import java.io.Serializable;
//---------------------------------------------------------------------------------------
//Name: Class declaration.
//---------------------------------------------------------------------------------------
public class Plane implements Comparable, Serializable
{
//---------------------------------------------------------------------------------------
// Variable declarations.
//---------------------------------------------------------------------------------------
private String flightNumber;
public String airlineName;
private double fuelRemaining;
private int overdue;
private int passengerNumber;
//---------------------------------------------------------------------------------------
// Enum declaration.
//---------------------------------------------------------------------------------------
private AIRPLANETYPE planeType;
private boolean isLanded = false;
public double timeLimitBeforeLand;
//---------------------------------------------------------------------------------------
// Enum Constuctor.
//---------------------------------------------------------------------------------------
public enum AIRPLANETYPE
{
AIRBUS("1"), CORPORATE("2"), PRIVATE("3");
private String planeName;
private AIRPLANETYPE(String planeName)
{
this.planeName = planeName;
}
public String getPlaneName()
{
return this.planeName;
}
}
//---------------------------------------------------------------------------------------
// Constructor.
//---------------------------------------------------------------------------------------
public Plane(String flightNumber, String airlineName,
double fuelRemaining, int overdue, int passengerNumber,
AIRPLANETYPE planeType, boolean isLanded)
{
this.flightNumber = flightNumber;
this.airlineName = airlineName;
this.fuelRemaining = fuelRemaining;
this.passengerNumber = passengerNumber;
this.overdue = overdue;
this.planeType = planeType;
this.isLanded = isLanded;
}
//---------------------------------------------------------------------------------------
// Getters and Setters.
//---------------------------------------------------------------------------------------
public String getAirlineName()
{
return airlineName;
}
public void setAirlineName(String airlineName)
{
this.airlineName = airlineName;
}
public void setOverdue(int overdue)
{
this.overdue = overdue;
}
public int getOverdue()
{
return overdue;
}
public String getFlightNumber()
{
return flightNumber;
}
public void setFlightNumber(String flightNumber)
{
this.flightNumber = flightNumber;
}
public double getFuelRemaining()
{
return fuelRemaining;
}
public void setFuelRemaining(double fuelRemaining)
{
this.fuelRemaining = fuelRemaining;
}
public int getPassengerNumber()
{
return passengerNumber;
}
public void setPassengerNumber(int passengerNumber)
{
this.passengerNumber = passengerNumber;
}
public AIRPLANETYPE getPlaneType()
{
return planeType;
}
public void setPlaneType(AIRPLANETYPE planeType)
{
this.planeType = planeType;
}
public boolean isLanded()
{
return isLanded;
}
public void setLanded(boolean isLanded)
{
this.isLanded = isLanded;
}
public double getLimitBeforeLand()
{
return timeLimitBeforeLand;
}
public void setTimeLimitBeforeLand(double timeLimitBeforeLand)
{
this.timeLimitBeforeLand = timeLimitBeforeLand;
}
//---------------------------------------------------------------------------------------
// CompareTo() used with the Comparable implementation.
//---------------------------------------------------------------------------------------
public int compareTo(Object arg0)
{
if((arg0 != null) && (arg0 instanceof Plane))
{
Plane p = (Plane) arg0;
return (int)Math.ceil(this.timeLimitBeforeLand - p.getLimitBeforeLand());
}
return 0;
}
//---------------------------------------------------------------------------------------
// toString().
//---------------------------------------------------------------------------------------
public String toString()
{
return "Plane: flightNumber=" + flightNumber + "."
+ " airlineName=" + airlineName + "."
+ " fuelRemaining=" + fuelRemaining + " litres."
+ " overdue=" + overdue + " minutes."
+ " passengerNumber="+ passengerNumber + "."
+ " airplaneType=" + planeType +
"hasLanded=" + isLanded+ ".\n";
}
}
The second argument in Collections.sort is for a Comparator not a Plane. Since I saw no mention of a Comparator, you should be able to use the natural order (defined by the compareTo method in your Plane object) and not have a second argument in the Collections.sort
EDIT: Unless you have just excluded that code, you aren't creating any Plane instances and you're using empty collections here...
TreeMap<String, PlaneStore> map = new TreeMap<String, PlaneStore>();
ArrayList<Plane> copyList = new ArrayList<Plane>(map.);
and you will be sorting by PlaneStores so you have to obtain all the Planes in each PlaneStore and add them to your copyList before sorting.
I would consider researching each of the Collections a little more and deciding what the best one for your need would be.