Access items from a stack using for

Asked

Viewed 612 times

5

I’m trying to access a forward position in the pile to make a comparison, but it’s not working and I couldn’t understand this for.

Code

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

Comparison I wanted to make

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

     }
}

Can anyone tell me anything?

2 answers

5


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");
   }
}
  • 3

    In Java, it’s called Enhanced For or "Is improved".

  • 2

    @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.

  • 1

    I cannot use length =/ already tried error, I declared "Pilhatokens = new Stack<String>();"

  • 2

    @Omaths in your case, Stack is a class of Collections, replace the length for size(), and instead of PilhaTokens[i], use PilhaTokens.get(i)

  • 2

    @Diegof Muuito Thanks meesmo! seriously! kkk has no idea how tired I had to look for it! xD

4

Omaths,

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

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

Pilhatokens = String List
Umtoken = variable
String = List type

Follow a more didactic reference. http://www.javaprogressivo.net/2012/09/o-laco-for-para-arrays.html

I hope I’ve helped!

Browser other questions tagged

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