Home > Back-end >  Finding min and max value in a oop
Finding min and max value in a oop

Time:12-15

Can I please get help with this java code? I am trying to output the min and max value of element from an array list but it's only outputting the first element added to the list and the last element added to the list. Can someone please tell me what the error might be? Here is my code:

import java.util.ArrayList;
//import java.util.Collections;

public class SolarSystem {
    private String solarName;
    private ArrayList<Planet> planetList = new ArrayList<>();

    public SolarSystem(String name) {
        solarName = name;
    }

    public String getSolarName() {
        return solarName;
    }

    public void addPlanet(Planet planet) {
        planetList.add(planet);
    }

    public void addPlanet(String planet, double dist) {
        planetList.add(new Planet(planet, dist));
    }

    public boolean havePlanet(String planet, double dist) {
        return planetList.contains(new Planet(planet, dist));
    }

    public Planet getPlanetByName(String planetName) {
        String planet = planetName;
        for (Planet elem : planetList) {
            planet  = elem;
            return elem;
        }
        return null;
    }

    public Planet closest() {
        Planet min = planetList.get(0);
        for (int i = 1; i > planetList.size(); i  ) {
            Planet minDist = planetList.get(i);
            if (min.equals(minDist)) {
                min = planetList.get(i);
            }
        }
        return min;
    }
    public Planet furthest() {
        Planet max  = planetList.get(0);
        for (int i = 0; i < planetList.size(); i  ) {
            Planet maxDist = planetList.get(i);
            if (max.equals(maxDist)) {
                max = planetList.get(i);
            }
        }
        return max;
    }

    @Override
    public String toString() {
        String solar = "Star "   solarName   " has planets:\n";
        for (Planet elem : planetList){
            solar  = elem.toString();
        }
        return solar;
    }

}

CodePudding user response:

From names being employed I believe you intend to compare by 'distance' (presumably distance from Sun?). Assuming this to be true and that the Planet class includes a getDistanceFromSun() method then you can do something like this. Finding the furthest Planet would work the same way except you switch the operator (or swap the operands).

public Planet findClosestToSun() {
  Planet closest = null;
  for (Planet planet : planets) {
    if (null == closest || planet.getDistanceFromSun() < closest.getDistanceFromSun()) {
      closest = planet;
    }
  }
  return closest;
}
  • Related