foreach不适用于表达类型

Rub*_*den 8 java

这个错误是什么意思?我该如何解决?

foreach不适用于表达类型.

我正在尝试编写一个方法find().在链表中找到一个字符串

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的全部代码

Ale*_*dam 11

您使用的是迭代器而不是数组吗?

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

你不能只是传入一个Iterator增强的for循环.以下第二行将生成编译错误:

    Iterator<Penguin> it = colony.getPenguins();
    for (Penguin p : it) {
Run Code Online (Sandbox Code Playgroud)

错误:

    BadColony.java:36: foreach not applicable to expression type
        for (Penguin p : it) {
Run Code Online (Sandbox Code Playgroud)

我刚看到你有自己的Stack类.您确实意识到SDK中已有一个,对吧?http://download.oracle.com/javase/6/docs/api/java/util/Stack.html 您需要实现Iterable界面才能使用这种形式的for循环:http://download.oracle.com/ JavaSE的/ 6 /文档/ API /爪哇/郎/ Iterable.html


Bal*_*a R 2

确保你的 for 结构看起来像这样

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

    for(String item : stringList)
    {
        // do something with item
    }
Run Code Online (Sandbox Code Playgroud)