foreach不适用于表达类型

foreach不适用于表达类型

本文介绍了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?

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

错误:

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


我刚看到你有自己的Stack类。您确实意识到SDK中已有一个,对吧?
您需要实现 Iterable 界面才能使用此格式的 for loop:

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.htmlYou 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不适用于表达类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 21:03