Chris <spam_me_not@goaway.com> writes:
Thank you. That is more elegant. In cases where a sentinel is possible,
it can work. It does do a peek() at the next element, though, which
won't work in many cases in my code.
OK, I remove the sentinel and the peek:
public class Main
{
final static java.lang.String source[] =
{ "A", "A", "A", "B", "B", "C", "D", "D" };
static int position = 0;
static java.lang.String getNext(){ return source[ position++ ]; }
static boolean hasNext(){ return position < source.length; }
public static void main( final java.lang.String[] args )
{ java.lang.String first = null;
java.lang.String next = null;
while( true )
{ if( next != null ){ first = next; next = null; }
else if( hasNext() )first = getNext(); else break;
int count = 1;
while( true )if( !hasNext() ){ next = null; break; }
else if( first.equals( next = getNext() ))++count; else break;
java.lang.System.out.println( "\"" + first + "\", " + count ); }}}
This is so complicated compared to Arne's suggestion of using a Map.