Loop counter is not increasing

1

I'm having a hard time finding the error in a logic that I use for to traverse 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 the same answer, as if x had not autoincrementado, could someone explain the problem? Thankful.

    
asked by anonymous 26.09.2017 / 21:31

2 answers

5

x is being initialized within foreach . This way, with each iteration ( loop ) it is initialized with value 0.

The solution would be to declare x out of loop .

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

Although the code above is right, it does not 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 the case) with an item in the list. >

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

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

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

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

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

    
26.09.2017 / 21:36
1

Try this:

  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());
  }
    
26.09.2017 / 21:36