Loop counter is not incrementing

Asked

Viewed 53 times

1

I’m having a hard time finding the error in a logic that I use for traversing an arraylist.

  List<Caneta> canetas = new ArrayList<>(); 
  canetas.add(c1);
  canetas.add(c2);

  System.out.print(Arrays.toString(canetas.toArray()));

  for (Caneta caneta : canetas) {
    int x = 0;
    System.out.printf(canetas.get(x).getModelo());
    x++; 
  }

The Sout returns me the same answer, as if the x had not self-improved, could someone explain the problem to me? Grateful.

  • Show the creation code of c1 and c2

  • 3

    You must declare the x out of the loop for, the way it is reset to each iteration

  • To go through the list with for each is not required counter, each loop is already incremented. In the translation for each is 'for each'.

2 answers

5


The x is being initialized within the foreach. In this way, with each iteration (loop) it is initialized with the value 0.

The solution would be to declare the x outside the loop.

int x = 0;
for (Caneta caneta : canetas) {
    System.out.printf(canetas.get(x).getModelo());
    x++; 
}

Although the above code is right, it doesn’t make much sense. The foreach is used to "pass" through all the elements of a collection and, at each loop, feed the variable (caneta, in case) with a list item.

So if you need to use the get(x), it would be better to use a for.

for(int x = 0; i < canetas.size(), x++) {
    System.out.printf(canetas.get(x).getModelo());
}

Or, if you want to continue using the "foreach", should do so

for(Caneta caneta : canetas){
     System.out.printf(caneta.getModelo());
}

You might be interested in reading this question: What are the syntax of the for loop in java?

1

Try this way:

  List<Caneta> canetas = new ArrayList<>(); 
  canetas.add(c1);
  canetas.add(c2);

  System.out.print(Arrays.toString(canetas.toArray()));

  for (Caneta caneta : canetas) {
    System.out.printf(caneta.getModelo());
  }
  • 1

    Even though you actually used the foreach, you kept that x the same way. It would be good to give a minimal explanation about the functioning of the foreach loop for the OP

  • I may have kept it, but mine will go through the list.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.