Foreach Not Applicable to Expression Type

what does this error mean? and how do i solve it?

foreach not applicable to expression type.

im am trying to write a method find(). that find a string in a linkedlist

public class Stack<Item>
{
    private Node first;

    private class Node
    {
        Item item;
        Node next;
    }

    public boolean isEmpty()
    {
        return ( first == null );
    }

    public void push( Item item )
    {
        Node oldfirst = first;
        first = new Node();
        first.item = item;
        first.next = oldfirst;
    }

    public Item pop()
    {
        Item item = first.item;
        first = first.next;
        return item;
    }
}


public find
{
    public static void main( String[] args )
    {
    Stack<String> s = new Stack<String>();

    String key = "be";

    while( !StdIn.isEmpty() )
        {
        String item = StdIn.readString();
        if( !item.equals("-") )
            s.push( item );
        else 
            StdOut.print( s.pop() + " " );
        }

    s.find1( s, key );
     }

     public boolean find1( Stack<String> s, String key )
    {
    for( String item : s )
        {
        if( item.equals( key ) )
            return true;
        }
    return false;
    }
}

this is all my code

7

3 Answers

Are you using an iterator instead of an array?

You cannot just pass an Iterator into the enhanced for-loop. The 2nd line of the following will generate a compilation error:

    Iterator<Penguin> it = colony.getPenguins();
    for (Penguin p : it) {

The error:

    BadColony.java:36: foreach not applicable to expression type
        for (Penguin p : it) {

I just saw that you have your own Stack class. You do realize that there is one already in the SDK, right? You need to implement Iterable interface in order to use this form of the for loop:

0

Make sure your for-construct looks like this

    LinkedList<String> stringList = new  LinkedList<String>();
    //populate stringList

    for(String item : stringList)
    {
        // do something with item
    }
0

Without code this is just a grasp at straws.

If you're trying to write your own list-find method, it would be like this

<E> boolean contains(E e, List<E> list) {

    for(E v : list) if(v.equals(e)) return true;
    return false;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest