0

Trying to return only the references(IW1, SS2) in the getUFFleet() however it is returning every single value of the toString(). MethodsgetUFFleet() and setupForces are from the same class while the toString from another class FYI.

public String getUFFleet()
    {
        System.out.println(ForceDetails.toString());
        
        return "No forces in UFF";
      
    }
private void setupForces()
    {
        ForceDetails.add(new starShip("IW1","Twisters",200,200,10,0,0,"No","Wing" +"\n"));
        ForceDetails.add(new starShip("SS2","Enterprise",300,200,0,10,20,"No","Starship"));
  
    }
   public String toString()
    {
        String s;
        s = "\nForce reference: " + FleetRef + "\nName: " + FullName +
            "\nActivation Fee: " + ActivationFee +"\nStrikers: "
            + Strikers + "\nLaser Canons: " + LaserCanon + "\nPhotonTorpedoes: "
            + PhotonTorpedoes + "\nStregth: "+ BattleStrength
            +"\nCloaking: " + Cloaking + "\nForce Type: " + ForceType +"\n";
        return s;
    }
  • Sorry, I don't undersand. What do you mean with `every single value of the toString()`? – gmanjon Dec 15 '21 at 00:32
  • @gmanjon my output is ```FleetRef``` ```FullName``` ```ActivationFee``` ```Strikers``` ```LaserCanon```etc. id like my output to be only ```FleetRef``` –  Dec 15 '21 at 00:34
  • Isn't enough changing the `toString` method to this single line? `return "Force reference: " + FleetRef;`? – gmanjon Dec 15 '21 at 00:38
  • @gmanjon i need the other values for other methods –  Dec 15 '21 at 00:40

1 Answers1

1

You can try to loop trough:

public String getUFFleet(){
    ForceDetails.forEach((starShip data) -> {
        System.out.println(data.getFleetRef());
      }
    );

    return "No forces in UFF";
}

as extra information about forEach loops see following link: Foreach loop in java for a custom object list

Yusuf gndz
  • 137
  • 10
  • in the ```getUFFleet``` method? –  Dec 15 '21 at 00:39
  • @Abbas did it work? if it doesn't work check https://stackoverflow.com/questions/13520571/foreach-loop-in-java-for-a-custom-object-list for more detailed forEach explanations and implement from the explanation. – Yusuf gndz Dec 15 '21 at 00:51
  • works perfectly –  Dec 15 '21 at 00:54
  • is there a way for it to iterate through ```ForceDetails``` and see if the list empty, and if it is the output will be ```No such forces in UFF```. because im getting this message although the list full –  Dec 15 '21 at 00:57
  • You can check if list is empty. just do something like `ForceDetails.isEmpty()` it will return a boolean value based on the condition. Check this non official link about arraylist functions from https://www.javatpoint.com/java-arraylist – Yusuf gndz Dec 15 '21 at 01:02
  • @Abbas it is also a good practice to check null or empty in first line of the function because rest of the code will not get executed if the something is empty. – Yusuf gndz Dec 15 '21 at 01:09