Access items from a stack using for

5

I'm trying to access a position forward in the stack to make a comparison, but it's not working and I could not understand this for .

Code

for ( String UmToken : PilhaTokens) 
{
    System.out.println(UmToken);
}

Comparison I wanted to do

for ( String UmToken : PilhaTokens) 
{
     if(listaReserva.contains(UmToken) && listaOperadores.contains(UmToken+1))
     {
         System.out.println("Variavel com nome de Palavra Reservada");

     }
}

Does anyone know how to tell me something to explain it or suggest something to me?

    
asked by anonymous 08.04.2016 / 22:27

2 answers

5

This type of loop is known as foreach and as can be seen in this @bigown response , it was made to traverse a sequence of data from beginning to end. It is usually used to move through a list, where the index is not so 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 traditional for , starting the index from 1 to the end, so you can compare in a more "elegant" way by comparing the current item with the previous one. Here's 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]);
    }

Output:

  

Previous value: a - Current value: b
  Previous value: b - Current value: c
  Previous value: c - Current value: d

See working at 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");
   }
}
    
08.04.2016 / 23:16
4

OMaths,

This "for" is called "foreach", it server to traverse its entire object from start to finish. You access the value of your object traversed by the "variable" you created.

for ( String UmToken : PilhaTokens) 
{
    System.out.println(UmToken);
}

PilotTokens = String List
UmToken = variable
String = List Type

A more didactic reference follows. link

I hope I have helped!

    
08.04.2016 / 22:51