This type of loop is known as foreach
and how it can be seen in this @Maniero response, it was made to go through a sequence of data from start to finish. It is usually used to scroll through a list, where the index is not as important to what needs to be done in iterations (such as just displaying items in sequence).
As an alternative to the problem presented, you can use the for
traditional, starting with the Dice from 1 to the end, so you can make the comparison more "elegant" by comparing the current item with the previous one. Take an example:
String[] array = {"a","b","c","d"};
for(int i = 1; i < array.length; i++){
System.out.print("Valor anterior: " + array[i-1]);
System.out.print(" - ");
System.out.println("Valor atual: " + array[i]);
}
Exit:
Previous value: a - Current value: b
Previous value: b - Current value: c
Previous value: c - Current value: d
See working on IDEONE.
Adapting to your code would look like this:
for(int i = 1; i < PilhaTokens.size(); i++){
if(listaReserva.contains(PilhaToken.get(i)) &&
listaOperadores.contains(PilhaToken.get(i-1))){
System.out.println("Variavel com nome de Palavra Reservada");
}
}
In Java, it’s called Enhanced For or "Is improved".
– Pablo Almeida
@Pabloalmeida not to give the idea that the name was
foreach
, modified the text. As the other answer already gave an explanation, I only supplemented with an example to solve the question problem.– user28595
I cannot use length =/ already tried error, I declared "Pilhatokens = new Stack<String>();"
– OMaths
@Omaths in your case, Stack is a class of Collections, replace the
length
forsize()
, and instead ofPilhaTokens[i]
, usePilhaTokens.get(i)
– user28595
@Diegof Muuito Thanks meesmo! seriously! kkk has no idea how tired I had to look for it! xD
– OMaths