Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

for loops & for each loops?

Below is a 'for each' loop. Under it is a few ways to write the same code but in 'for loop' version and as a 'while loop'. Are they correct?

String[] cities = new String[ 10 ];

// missing code that inserts a String in each element of this array

for ( String city : cities )

{

if ( city.substring( 0, 1 ).equals( "C" ) )

System.out.println( city );

}

Can it be re-written as :

String[] cities = new String[ 10 ];

// missing code that inserts a String in each element of this array

for ( int i = 0 ; i < cities.length ; i++ )

{

String city = cities[ i ];

if ( city.substring( 0, 1 ).equals( "C" ) )

System.out.println( city );

}

and

String[] cities = new String[ 10 ];

// missing code that inserts a String in each element of this array

for ( int i = 0 ; i < cities.length ; i++ )

{

if ( cities[ i ].substring( 0, 1 ).equals( "C" ) )

System.out.println( cities[ i ] );

}

and

(while loop..)

String[] cities = new String[ 10 ];

// missing code that inserts a String in each element of this array

int i = 0;

while ( i < cities.length )

{

String city = cities[ i ];

if ( city.substring( 0, 1 ).equals( "C" ) )

System.out.println( city );

i++;

}

2 Answers

Relevance
  • Anonymous
    1 decade ago

    You're making two invalid assumptions - that you'll know how many elements there are and that they can be enumerated. If that's the case it wouldn't be written as a for each to begin with. (In your second example, you're defining a string inside the loop - never do anything inside a loop that can be done outside it or that can be done a cheaper way. Repeated code is expensive code. if ( cities[i].substring( 0, 1 ).equals( "C" ) ) )

  • 1 decade ago

    Probably quicker to compile and look for errors?

Still have questions? Get your answers by asking now.