foreach不适用于表达类型

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

foreach不适用于表达类型。

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

public class Stack { 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 s = new Stack(); 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 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

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

  Iterator 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循环的这种forms: http : //download.oracle。 COM / JavaSE的/ 6 /文档/ API /爪哇/郎/ Iterable.html

确保你的for-construct看起来像这样

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

没有代码,这只是对稻草的把握。

如果你正在尝试编写自己的list-find方法,那就像这样

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