2011-04-25 139 views
4

这个错误是什么意思?我如何解决它?foreach不适用于表达式

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

这是我的所有代码

+6

如果你表现出你的代码,这将有助于。 – Jonas 2011-04-25 21:13:47

+0

你可以请张贴一些代码吗? – ryanprayogo 2011-04-25 21:14:05

+0

如果你的成绩很好,你是否赞成答案? – 2011-04-25 21:27:08

回答

2

确保你的,结构是这样的

LinkedList<String> stringList = new LinkedList<String>(); 
    //populate stringList 

    for(String item : stringList) 
    { 
     // do something with item 
    } 
+0

其完全一样 – 2011-04-25 21:24:34

9

您是否使用了迭代器,而不是一个数组的?

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 你需要实现以使用这种形式的for循环Iterable接口:http://download.oracle.com/javase/6/docs/api/java/lang/Iterable.html

+0

您应该可以遍历Stack ... – Aleadam 2011-04-25 21:43:48

0

没有代码这仅仅是救命稻草把握。

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

<E> boolean contains(E e, List<E> list) { 

    for(E v : list) if(v.equals(e)) return true; 
    return false; 
} 
相关问题