-4

Basically I want to know how to apply an if condition to every element of an arraylist. Here's my code.

   System.out.println("Type positive integers less than 40: ");

    ArrayList<Integer> inRay = new ArrayList<Integer>();
    Scanner sc = new Scanner(System.in);
    while (sc.hasNext())
    {
        inRay.add(sc.nextInt());
    }

    //this is where the problem starts//

    int i;
    if (inRay.get(i) > 40)
    {
        System.out.println("You had one job.");
        System.exit(0);
    }

I would like to apply an if condition where if a value in the array list is over 40, it exits.

user3591265
  • 7
  • 1
  • 1
  • 1

2 Answers2

0

Replace the line where you are declaring 'i' with a for loop that starts from 0 and goes up to iRay.size().

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

In this for loop, the portion before the first semi-colon, declare and initialize a counter variable to 0. After the first semi-colon is the condition up to which the loop should repeat, and after the second semi-colon, is the increment of the counter.

Andrew Lobley
  • 342
  • 4
  • 12
0

You need to iterate over the ArrayList like this:

for (int i : inRay)
    if (i > 40) {
        System.out.println("You had one job.");
        System.exit(0);
    }

In general, if you want to do something for every element of an array list, do this:

for (Type t : list) {
    // do something involving t
}

You need the actual type of the array list elements instead of Type.

tbodt
  • 16,609
  • 6
  • 58
  • 83