Home > database >  Can't loop properly through list of objects
Can't loop properly through list of objects

Time:01-21

I'm having the following issue. I have a list filled with instances of the "God" class, 12 instances, for now, but will add more in the future.

I also have an list empty. Both lists can take type God instances.

The user will pick 6 of these gods, and these gods will be added to the empty list, and also be remove of the filled list, so they can't get picked again.

The goal of this part of the project is, to:

  1. The user will pick 6 times. So I have a for loop from 0 to 5;
  2. The Scanner takes the id of the god
  3. The second for loop, from 0 to listFilledWithGods.size(), will check if the scanner matches the id
  4. If the id matches, it will add to the empty list, and remove from the List filled with gods
  5. If it does not match the user needs to be asked constantly to pick another one, until the user picks an available god. (here is where I'm having trouble)

Github: https://github.com/OrlandoVSilva/battleSimulatorJava.git

  • The issue in question resides in the class player in the method selectGodsForTeam
  • There is a JSON jar added to the project: json-simple-1.1.1

*Edit:

I added the while loop, as an exmaple of one of the ways that I tried to fix the issue.

If the user on the first pick picks id 3, it should work, because no god has been picked yet, however the loop when comparing it with the first position (id 1) it says to pick another one, which should is not the intended objective.

Main:

import java.util.List;

public class Main {
    public Main() {
    }

    public static void main(String[] args) {
        Launcher launch = new Launcher();
        godSelection(launch.loadGods());
    }

    private static void godSelection(List<God> listOfloadedGods) {
        Player player = new Player(listOfloadedGods);
        player.selectGodsForTeam();
    }
}

Launcher:

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

public class Launcher {
    private List<God> godCollection;

    public Launcher(){
        godCollection = new ArrayList<>();
    }

    List<God> loadGods(){ // load all gods from Json file into list
        String strJson = getJSONFromFile("C:\\Users\\OrlandoVSilva\\Desktop\\JavaBattleSimulator\\battlesimulator\\src\\projectStructure\\gods.json");

        // Try-catch block
        try {
            JSONParser parser = new JSONParser();
            Object object = parser.parse(strJson); // converting the contents of the file into an object
            JSONObject mainJsonObject = (JSONObject) object; // converting the object into a json object
            //-------------------
            JSONArray jsonArrayGods = (JSONArray) mainJsonObject.get("gods");
            //System.out.println("Gods: ");

            for(int i = 0; i < jsonArrayGods.size(); i  ){
                JSONObject jsonGodsData = (JSONObject) jsonArrayGods.get(i);

                String godName = (String) jsonGodsData.get("name");
                //System.out.println("Name: "   godName);

                double godHealth = (double) jsonGodsData.get("health");
                //System.out.println("Health: "   godHealth);

                double godAttack = (double) jsonGodsData.get("attack");
                //System.out.println("Attack: "   godAttack);

                double godSpecialAttack = (double) jsonGodsData.get("specialAttack");
                //System.out.println("Special Attack: "   godSpecialAttack);

                double godDefense = (double) jsonGodsData.get("defense");
                //System.out.println("Defense: "   godDefense);

                double godSpecialDefence = (double) jsonGodsData.get("specialDefense");
                //System.out.println("Special Defence: "   godSpecialDefence);

                double godSpeed = (double) jsonGodsData.get("speed");
                //System.out.println("Speed: "   godSpeed);

                double godMana = (double) jsonGodsData.get("mana");
                //System.out.println("Mana: "   godMana);

                String godPantheon = (String) jsonGodsData.get("pantheon");
                //System.out.println("Pantheon: "   godPantheon);

                long godId = (long) jsonGodsData.get("id");
                int newGodId = (int) godId;
                //System.out.println("Id: "   newGodId);

                godCollection.add(new God(godName, godHealth, godAttack, godSpecialAttack, godDefense, godSpecialDefence, godSpeed, godMana, godPantheon, newGodId));
                //System.out.println();
            }

        } catch (Exception ex){
            ex.printStackTrace();
        }
        // Try-catch block

        //System.out.println("Size: "   godCollection.size());
        return godCollection;
    }

    public static String getJSONFromFile(String filename) { // requires file name
        String jsonText = "";
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(filename)); // read the file

            String line; // read the file line by line
            while ((line = bufferedReader.readLine()) != null) {
                jsonText  = line   "\n"; // store json dat into "jsonText" variable
            }

            bufferedReader.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return jsonText;
    }
}

Player:

import java.util.*;

public class Player {
    // --- Properties ---
    private List<God> listOfAllGods; // List of all the gods;
    private List<God> selectedGods; // list for the selected gods;
    // --- Properties ---

    // --- Constructor ---
    Player(List<God> listOfAllGods){
        this.listOfAllGods = listOfAllGods;
        selectedGods = new ArrayList<>();
    }
    // --- Constructor ---

    // --- Getters & Setters ---
    public List<God> getSelectedGods() {
        return listOfAllGods;
    }
    // --- Getters & Setters ---

    // --- Methods ---
    void selectGodsForTeam(){
        Scanner scanner = new Scanner(System.in);
        boolean isGodAvailable;
        int chooseGodId;

        /*
        char answerChar = 'n';

        while (answerChar == 'n'){
            answerChar = informationAboutGods();
            // Do you want to see information about any of the gods first?
            // y or n

            while(answerChar == 'y'){
                answerChar = informationAboutAnyOtherGods();
                // Which of the gods, do you want to see information of?
                // godId
                // Do you want to see information about any other gods?
                // y or n
            }
            answerChar = proceedWithGodPick();
            // Do you want to proceed with the God pick?
            // y or n
        }

        System.out.println();
        */

        System.out.println("Please choose the 6 id's of the gods, you wish to pick:");
        for(int i = 0; i <= 5; i  ){
            chooseGodId = scanner.nextInt();

            for(int j = 0; j < listOfAllGods.size(); j  ){
                if(chooseGodId == listOfAllGods.get(j).getId()){
                    selectedGods.add(listOfAllGods.get(j));
                    listOfAllGods.remove(j);
                } else {
                    isGodAvailable = false;
                    while (!isGodAvailable){
                        System.out.println("Please pick another one");
                        chooseGodId = scanner.nextInt();

                        if(chooseGodId == listOfAllGods.get(j).getId()) {
                            isGodAvailable = true;
                            selectedGods.add(listOfAllGods.get(j));
                            listOfAllGods.remove(j);
                        }
                    }
                }
            }
        }
    }

    char informationAboutGods(){
        Scanner scanner = new Scanner(System.in);
        char answerChar = 'n';
        //-----------

        System.out.println("This is a list, of all the selectable gods: ");
        System.out.println();

        for (int i = 0; i < listOfAllGods.size(); i  ){
            System.out.println(listOfAllGods.get(i).getName()   " = "   "Id: "   listOfAllGods.get(i).getId());
        }
        System.out.println();

        System.out.println("Do you want to see information about any of the gods first?");
        System.out.println("[y] or [n]");
        answerChar = scanner.next().charAt(0);

        return answerChar;
    }
    char informationAboutAnyOtherGods(){
        Scanner scanner = new Scanner(System.in);
        char answerChar = 'n';
        int answerInt;
        //------------

        System.out.println();
        System.out.println("Which of the gods, do you want to see information of?");
        System.out.println("Please input it's id number: ");
        answerInt = scanner.nextInt();

        System.out.println();
        System.out.println("Display god information here!");
        System.out.println();

        System.out.println("Do you want to see information about any other gods?");
        System.out.println("[y] or [n]");
        answerChar = scanner.next().charAt(0);

        return answerChar;
    }
    char proceedWithGodPick(){
        Scanner scanner = new Scanner(System.in);
        char answerChar = 'n';
        //----------

        System.out.println();
        System.out.println("Do you want to proceed with the God pick?");
        System.out.println("[y] or [n]");
        answerChar = scanner.next().charAt(0);

        return answerChar;
    }
    // --- Methods ---
}

God:

public class God {
    private final String name;
    private double health;
    private double attack;
    private double specialAttack;
    private double defense;
    private double specialDefense;
    private double speed;
    private double mana;
    private final String pantheon;
    private final int id;

    public God(String name, double health, double attack, double specialAttack, double defense, double specialDefense, double speed, double mana, String pantheon, int id) {
        this.name = name;
        this.health = health;
        this.attack = attack;
        this.specialAttack = specialAttack;
        this.defense = defense;
        this.specialDefense = specialDefense;
        this.speed = speed;
        this.mana = mana;
        this.pantheon = pantheon;
        this.id = id;
    }

    public double getHealth() {
        return this.health;
    }

    public void setHealth(double health) {
        this.health = health;
    }

    public double getAttack() {
        return this.attack;
    }

    public void setAttack(double attack) {
        this.attack = attack;
    }

    public double getSpecialAttack() {
        return this.specialAttack;
    }

    public void setSpecialAttack(double specialAttack) {
        this.specialAttack = specialAttack;
    }

    public double getDefense() {
        return this.defense;
    }

    public void setDefense(double defense) {
        this.defense = defense;
    }

    public double getSpecialDefense() {
        return this.specialDefense;
    }

    public void setSpecialDefense(double specialDefense) {
        this.specialDefense = specialDefense;
    }

    public double getSpeed() {
        return this.speed;
    }

    public void setSpeed(double speed) {
        this.speed = speed;
    }

    public double getMana() {
        return this.mana;
    }

    public void setMana(double mana) {
        this.mana = mana;
    }

    public String getName() {
        return this.name;
    }

    public String getPantheon() {
        return this.pantheon;
    }

    public int getId() {
        return this.id;
    }
}

CodePudding user response:

If I understand correctly, the key is to replace the for loop, which will have 6 iterations, with a while loop, which will iterate until the user has successfully selected 6 gods. Use continue; when there is a failure to select a god.

System.out.println("Please choose the 6 id's of the gods, you wish to pick:");
    while (selectedGods.size () < 6) {        
        System.out.print ("You have selected "   selectedGods.size () 
            "gods. Please enter I.D. of next god >");
        chooseGodId = scanner.nextInt();
        if (findGod (selectedGods, chooseGodID) >= 0) { 
           System.out.println ("You already selected god "   chooseGodId
              ".  Please select again.");
           continue;
        }
        int godSelectedIndex = findGod (listOfAllGods, chooseGodId);
        if (godSelectedIndex < 0) { 
           System.out.println ("God "   chooseGodID   " is not available."
               "  Please select again.");
           continue;
         }
         
         selectedGods.add (listOfAllGods.get(godSelectedIndex));
         listOfAllGods.remove (godSelectedIndex);
}

This assumes the existence of

  static public int findGod (List<God> godList, int targetGodID)

This findGod method searches godList for an element in which .getId() is equal to gargetGodID. When a match is found, it returns the index of element where the match was found. When a match is not found, it returns -1. The O/P has shown the ability to create this method.

Note: I have not verified the code in this answer. If you find an error, you may correct it by editing this answer.

  • Related