Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach not applicable to expression type

Tags:

java

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

like image 883
Ruben Van St Aden Avatar asked Apr 25 '11 21:04

Ruben Van St Aden


1 Answers

Are you using an iterator instead of an array?

http://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with

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? http://download.oracle.com/javase/6/docs/api/java/util/Stack.html You need to implement Iterable interface in order to use this form of the for loop: http://download.oracle.com/javase/6/docs/api/java/lang/Iterable.html

like image 137
Aleadam Avatar answered Sep 22 '22 18:09

Aleadam