deft VG
deft VG

Reputation: 1

Why does for loop not work with array.size()?

This is my first time here and I am quite new to coding on Android Studio. I am trying to fill up an ArrayList using for loop but my coding on the for loop has some issues. I am also not sure what information I have to show. I think the problem might be adding variables to the array in the loop. Some of my code:


for (int i = 0; i < foodis.size() ; i++) {

                if(beverage.get(i).getCalorie()>=(inputcalorie-100)&&beverage.get(i).getCalorie()<=(inputcalorie+100)){


                    foodtest=beverage.get(i).getFood();
                    calorietest=beverage.get(i).getCalorie();
                    Log.d("MyActivity","foodtest=" + foodtest);
                    Log.d("MyActivity","calorietest=" + calorietest);

                        foodis.add(new foodis(foodtest,calorietest));

                        Log.d("MyActivity","food=" + foodis.get(i).getFooddisplay());
                        Log.d("MyActivity","cal=" + foodis.get(i).getCaldisplay());


            }

Edit: I made an beveragearraylist with data from a csv file (shown below)

Coffee,0
Coffee With Milk,150
Milo,371
Milo 50% Less Sugar,140
Apple Juice,46
Orange Juice ,45
Milk,149
Low Fat Milk,110

Class foodis:


public class foodis {

    public String fooddisplay;
    public Double caldisplay;

    public foodis(String fooddisplay, Double caldisplay) {
        this.fooddisplay = fooddisplay;
        this.caldisplay = caldisplay;
    }

    public String getFooddisplay() {
        return fooddisplay;
    }

    public void setFooddisplay(String fooddisplay) {
        this.fooddisplay = fooddisplay;
    }

    public Double getCaldisplay() {
        return caldisplay;
    }

    public void setCaldisplay(Double caldisplay) {
        this.caldisplay = caldisplay;
    }

}

Class beverage:

public class beverage {
    private String food;
    private Double calorie;


    public String getFood() {

        return food;
    }

    public void setFood(String food) {

        this.food = food;
    }

    public Double getCalorie() {

        return calorie;
    }

    public void setCalorie(Double calorie)
    {
        this.calorie = calorie;
    }




    @Override
    public String toString() {
        return "FoodSample{" +
                ", food='" + food + '\'' +
                ", calorie=" + calorie +
                '}';
    }
}

Upvotes: 0

Views: 269

Answers (1)

AlenBer
AlenBer

Reputation: 748

Arrays in Java start from 0 (Zero), so foodis.size() will return 4 if there are 4 entries in the list but the index ends at 3 as it starts from 0.

java.lang.IndexOutOfBoundsException: Index: 3, Size: 3 

Upvotes: 3

Related Questions