这个错误是什么意思?我该如何解决?
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;
}
}
这是我所有的代码
最佳答案
您使用的是迭代器而不是数组吗?
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
您需要实现 Iterable
接口(interface)才能使用这种形式的 for
循环:http://download.oracle.com/javase/6/docs/api/java/lang/Iterable.html
关于java - foreach 不适用于表达式类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5783339/