Search code examples
javafor-loopbooleanmaxmin

Finding min and max value in a oop


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 ClassName{
    private String fieldName;
    private ArrayList<SubClass> list = new ArrayList<>();

    public ClassName(String a) {
        fieldName = a;
    }

    public String getFieldName() {
        return fieldName;
    }

    public void addSub(SubClass b) {
        list.add(b);
    }

    public void addSub(String b, double c) {
        list.add(new SubClass(b, c));
    }

    public boolean haveSub(String b, double c) {
        return list.contains(new SubClass(b, c));
    }

    public SubClass getSubByName(String b) {
        String d = b;
        for (Sub elem : list) {
            d += elem;
            return elem;
        }
        return null;
    }

    public SubClass closest() {
        SubClass min = list.get(0);
        for (int i = 1; i > list.size(); i++) {
            SubClass minC = list.get(i);
            if (min.equals(minC)) {
                min = list.get(i);
            }
        }
        return min;
    }
    public SubClassfurthest() {
        SubClass max  = list.get(0);
        for (int i = 0; i < list.size(); i++) {
            Planet maxC = list.get(i);
            if (max.equals(maxC)) {
                max = list.get(i);
            }
        }
        return max;
    }

    @Override
    public String toString() {
        String s = "...text..." + fieldName + " ...text...:\n";
        for (SubClass elem : list){
            s += elem.toString();
        }
        return s;
    }

}

Solution

  • 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;
    }