foreach不适用于表达类型 [英] foreach not applicable to expression type

查看:5051
本文介绍了foreach不适用于表达类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

foreach不适用于表达式类型。

foreach not applicable to expression type.

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

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

这是我的全部代码

推荐答案

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

Are you using an iterator instead of an array?

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


你不能只将 Iterator 传递给增强的for循环。以下第二行将生成编译错误:

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

错误:

    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 界面才能使用此格式的 for loop: http://download.oracle.com/javase/6/docs/api/java/lang/Iterable.html

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

这篇关于foreach不适用于表达类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆