java - foreach 不适用于表达式类型

标签 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;
    }
}

这是我所有的代码

最佳答案

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

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) {

我刚刚看到您有自己的 Stack 类。您确实意识到 SDK 中已经有一个,对吧? http://download.oracle.com/javase/6/docs/api/java/util/Stack.html 您需要实现 Iterable 接口(interface)才能使用这种形式的 for 循环:http://download.oracle.com/javase/6/docs/api/java/lang/Iterable.html

关于java - foreach 不适用于表达式类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5783339/

相关文章:

Java:委托(delegate)模式和 protected 方法

具有最终用户提供的字段的类的 Java 构造函数

java - 未编译的 Java 程序可以工作,但当 Coldfusion 从 'jar' 文件调用方法时会产生错误?

java - 查找字符在字母表中的位置

java - 当收到来自服务器的消息时,如何在 Android 客户端上启动新的 Activity

java - 停止 Spring MVC 获取 LazyLoad 数据

java - 为什么 await of Condition 会释放锁而 signal 不会?

java - 从同一包中的不同类调用新方法

java - 老虎机时间线动画不起作用

java - 具有图像叠加中心和滚动行为的工具栏