Foreach is not an expression type

What does this error mean? and how to solve it?

foreach is not an expression type.

im trying to write find () method. that find a string in a linked list

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

this is all my code

+4
source share
3 answers

Do you use an iterator instead of an array?

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

You cannot just pass Iterator to the extended for loop. The second line of the following will generate a compilation error:

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

Error:

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

I just saw that you have your own Stack class. You understand that there is one in the SDK, right? http://download.oracle.com/javase/6/docs/api/java/util/Stack.html You need to implement the Iterable interface in order to use this form of the for loop: http://download.oracle.com/javase/ 6 / docs / api / java / lang / Iterable.html

+9
source

Make sure your for-construct looks like this:

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

Without a code, it’s just enough for a straw.

If you are trying to write your own list search method, it will be like this:

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

All Articles