-2

I'm working on a school assignement where i have to check if certain objects from the ArrayList teKoop are not in the ArrayList mijnGames, the problem is i keep geeting this error code: Index 1 out of bounds for length 1

Is there anything obvious going wrong here?

Any help would be highly appreciated.

public ArrayList<Game> bepaalGamesNietInBezit(ArrayList<Game> teKoop) {
    ArrayList<Game> nogNietInBezit = new ArrayList<Game>();
    for (int i = 0; i <= mijnGames.size(); i++) {
        if (!mijnGames.get(i).getNaam().equals(teKoop.get(i).getNaam())) {
            nogNietInBezit.add(teKoop.get(i));
            return nogNietInBezit;

            }
        }
        return nogNietInBezit;

}

So indexOutOfBound error got fixed, new problem appears :S

It keeps returning me an empty ArrayList:

    private String naam;
    private int releaseJaar;
    private double nieuwprijs;
    private int ditJaar = LocalDate.now().getYear();```


    public Game(String nm, int rJ, double nwpr){
        this.naam = nm;
        this.releaseJaar = rJ;
        this.nieuwprijs = nwpr;

    }

    public String getNaam(){
        return naam;
    }

    public int getReleaseJaar(){
        return releaseJaar;
    }

    public double huidigeWaarde(){
        int jaarVerschil = ditJaar - releaseJaar;
        double nieuweWaarde = nieuwprijs;
        for (int i = 0; i < jaarVerschil; i++){
            nieuweWaarde = nieuweWaarde * 0.7;
        }
        return nieuweWaarde;
    }

    @Override
    public boolean equals(Object andereObject){
        boolean gelijkeObjecten = false;
        if (andereObject instanceof Game) {
            if (((Game) andereObject).getNaam().equals(naam) && ((Game) andereObject).getReleaseJaar() == releaseJaar){
                gelijkeObjecten = true;
            }
        }
        else {
            gelijkeObjecten = false;
        }
        return gelijkeObjecten;
    }


    @Override
    public String toString() {
        return String.format(naam + ", uitgegeven in " + releaseJaar + "; nieuwprijs: €%.2f nu voor: €%.2f", nieuwprijs, huidigeWaarde());
    }
}

```public class Persoon {
    private String naam;
    private double budget;
    private ArrayList<Game> mijnGames;```

    public Persoon(String nm, double bud) {
        this.naam = nm;
        this.budget = bud;
        mijnGames = new ArrayList<>();
    }

    public double getBudget() {
        return budget;
    }


    public boolean koop(Game nm){
        if (!mijnGames.contains(nm) && budget >= nm.huidigeWaarde()){
            mijnGames.add(nm);
            budget = budget - nm.huidigeWaarde();
            return true;
        }

        if (mijnGames.contains(nm) && budget < nm.huidigeWaarde()){
            System.out.println("Er is helaas iets verkeerd gegaan");
            return false;
        }

        if (mijnGames.contains(nm)){
            System.out.println("Je hebt deze game al :)");
            return false;
        }

        if (budget < nm.huidigeWaarde()){
            System.out.println("Helaas heb je niet genoeg budget voor deze game :(");
            return false;
        }

        else {
            return false;
        }

    }

    public boolean verkoop(Game g, Persoon koper){
        if (mijnGames.contains(g) && koper.budget >= g.huidigeWaarde() && !koper.mijnGames.contains(g)){
            budget = budget + g.huidigeWaarde();
            koper.budget = koper.budget - g.huidigeWaarde();
            mijnGames.remove(g);
            koper.mijnGames.add(g);
            return true;
        }
        else {
            return false;
        }
    }

    public Game zoekGameOpNaam(String nm){
        if (mijnGames.size() > 0){
            for (Game game: mijnGames){
                if (game.getNaam().equals(nm)){
                    return game;
                }
            }
        }

        return null;
    }
    

    @Override
    public String toString() {
        if (mijnGames.isEmpty()){
            return String.format(naam + " heeft een budget van " + "€%.2f" + " en bezit de volgende games:", budget);
        }
        else return String.format(naam + " heeft een budget van " + "€%.2f" + " en bezit de volgende games:\n" + mijnGames.toString().replace("[", "").replace("]", ""), budget);
    }

    public ArrayList<Game> bepaalGamesNietInBezit(ArrayList<Game> teKoop) {
        ArrayList<Game> nogNietInBezit = new ArrayList<Game>();
        for (int i = 0; i < mijnGames.size(); i++) {
            if (!mijnGames.contains(teKoop.get(i))) {
                nogNietInBezit.add(teKoop.get(i));
                return nogNietInBezit;
            }

        }
            return nogNietInBezit;

    }
}


public class Main {

    public static void main(String[] args) {
        int releaseJaar1 = LocalDate.now().getYear() - 1; // 1 jaar geleden

        Game g1 = new Game("Just Cause 3", releaseJaar1, 49.98);
        Game g2 = new Game("Need for Speed: Rivals", releaseJaar1, 45.99);
        Game g3 = new Game("Need for Speed: Rivals", releaseJaar1, 45.99);

        Persoon p1 = new Persoon("Eric", 200);
        Persoon p2 = new Persoon("Hans", 55);



        System.out.println("p1 koopt g1:" + (p1.koop(g1) ? "" : " niet") + " gelukt");
        System.out.println("p1 koopt g2:" + (p1.koop(g2) ? "" : " niet") + " gelukt");
        System.out.println("p1 koopt g3:" + (p1.koop(g3) ? "" : " niet") + " gelukt");
        System.out.println("\np1: " +p1+ "\n\np2: " +p2+ "\n");


        System.out.println("p1 verkoopt g2 aan p2:"+(p1.verkoop(g2, p2) ? "" : " niet")+" gelukt");
        System.out.println("p1 verkoopt g1 aan p2:"+(p1.verkoop(g1, p2) ? "" : " niet")+" gelukt");
        System.out.println("\np1: " +p1+ "\n\np2: " +p2+ "\n");

        Game game1 = p1.zoekGameOpNaam("Just Cause 3");
        System.out.println("p1 heeft Just Cause 3 " + (game1 != null ? "wel!" : "niet!"));

        ArrayList<Game> teKoop = new ArrayList<Game>();
        teKoop.add(g1);
        teKoop.add(new Game("Mario Kart 8", 2019, 35.00));
        ArrayList<Game> nogNietInBezit = p1.bepaalGamesNietInBezit(teKoop);
        System.out.println("p1 heeft de volgende games nog niet: " + nogNietInBezit.toString());


    }
}

I apolagise in advance for the code spam, but i have been working on this issue for 4 hours now.


Abra
  • 19,142
  • 7
  • 29
  • 41
aitsimhand
  • 13
  • 5
  • 2
    try with for (int i = 0; i < mijnGames.size(); i++) instead of for (int i = 0; i <= mijnGames.size(); i++) – dreamcrash Mar 06 '21 at 14:08
  • Read the problem again. The error is because of 0-based indexes so you need < rather than <=, but couldn't the arrays have the same content but in different order? You check only if the elements are equal at the same index. Hint - see contains method. – ewramner Mar 06 '21 at 14:14

2 Answers2

1

for (int i = 0; i <= 5 i++) {}

Go through that. That will loop once for each of these: 0, 1, 2, 3, 4, 5. Count em up. That's.. 6 loops. Not 5. That's because we started counting at 0. So, if mijnGames.size() returns 1, that would cause that loop to run twice: Once through, i will be 0, and another time through, i will be 1.

For the same reasons, a list with 1 item in it will give you one item if you invoke .get(0) on it, and will throw an IndexOutOfBoundsException if you invoke .get(1) on it, because .get(1) fetches the second item, and there is no such item in this list.

The two important maxims that many programming languages and libraries adopt, and java and just about every library every made for java also adopts:

  • Start at 0
  • Ranges are put in terms of 'start' and 'end' (and not 'end - 1' or what not)
  • The start of the range is inclusive.
  • The end of the range is exclusive.
  • The size of the range is 'end - start'.

See how it applies to arraylists:

  • They start at 0
  • The common way to frame a loop on index is: for (int i = 0; i < list.size(); i++)
  • The start is inclusive: i = 0.
  • The end is exclusive: Use < and not <= which is what is going wrong in your snippet.
  • After replacing <= with <, we have adhered to all the base rules, therefore, the size of what we cover is just end-start, so list.size() - 0, so: That loops once for each element in the list. Which is what we wanted.
rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
0

Indexes are zero-based. That means if you have a list with ten elements, their indices will be from 0 - 9 inclusive. The for-loop is declared as for (int i = 0; i <= mijnGames.size(); i++). A for loop works with three clauses, the init clause (i = 0), a condition (i <= mijnGames.size()) and an update at the end of each iteration (i++).

In plain English that means

Start counting from 0, up to, and including the size of the list (the number of elements). Since the indices however are 0-based, the program crashes with at out of bounds exception.

You can fix this by modifying your condition inside the for loop declaration to

for (int i = 0; i < mijnGames.size(); i++)
geco17
  • 5,152
  • 3
  • 21
  • 38