【问题标题】:foreach not applicable to expression typeforeach 不适用于表达式类型
【发布时间】:2011-04-25 21:11:51
【问题描述】:

这个错误是什么意思?以及如何解决?

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

这是我的全部代码

【问题讨论】:

  • 如果您显示您的代码会有所帮助。
  • 你能贴一些代码吗?
  • 如果你获得了好成绩,你会投票给答案吗?
  • 对我来说编译得很好。你用的是什么编译器?太阳的?
  • 问题是你的 Stack 类没有实现 Iterable,它没有覆盖 public iterator() 方法,因此当你这样做时没有迭代器传递给 for 循环:for String item : Stack&lt;String&gt; s)。您可以通过添加存储堆栈项的 HashSet、实现 Iterable 并覆盖迭代器方法以返回 HashSet 的迭代器来解决此问题。然后你应该能够在你的类上使用 for-each 循环。

标签: java


【解决方案1】:

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

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

您不能只将 Iterator 传递到增强的 for 循环中。以下第2行会产生编译错误:

    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 循环:http://download.oracle.com/javase/6/docs/api/java/lang/Iterable.html

【讨论】:

    【解决方案2】:

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

        LinkedList<String> stringList = new  LinkedList<String>();
        //populate stringList
    
        for(String item : stringList)
        {
            // do something with item
        }
    

    【讨论】:

      【解决方案3】:

      没有代码,这只是抓住稻草。

      如果你正在尝试编写自己的列表查找方法,它会是这样的

      <E> boolean contains(E e, List<E> list) {
      
          for(E v : list) if(v.equals(e)) return true;
          return false;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-25
        • 1970-01-01
        • 2012-10-21
        • 1970-01-01
        • 2021-11-16
        • 2023-03-15
        • 2012-06-15
        • 2018-06-24
        相关资源
        最近更新 更多