Explore BrainMass
Share

Explore BrainMass

    Explaining why using break and continue is a bad practice

    This content was COPIED from BrainMass.com - View the original, and get the already-completed solution here!

    This figure shows an example of using a command in Java called break and continue. I somewhat disagree with the use of these commands in this way. I consider it bad form as does much of the industry. Just because a command is there does not mean you have to use it!

    Why this is bad form and provide a snippet of code that shows a better way to code the loops in this example.

    I am actually using Jcreator to look at this code. You can either use Jcreator or Netbeans java program to do this one if you choose:
    _______________________________________________________________________

    // Fig. 5.12: BreakTest.java
    // break statement exiting a for statement.
    Public class BreakTest
    {
    Public static void main( String args[] )
    {
    int count; // control variable also used after loop terminates

    for ( count = 1; count <= 10; count++ ) // loop 10 times
    {
    if ( count == 5 ) // if count is 5,
    break;

    System.out.printf( "%d ", count );
    } // end for

    System.out.printf( "nBroke out of loop at count = %dn", count );
    } // end main
    } // end class BreakTest

    © BrainMass Inc. brainmass.com October 9, 2019, 10:58 pm ad1c9bdddf
    https://brainmass.com/computer-science/java/239350

    Solution Preview

    The break and continue statements can be used in useful situations but many times they are abused. The code shown in this example is one of the "abuse" cases. Notice that the for loop will iterate up until the count is equal to 5. At that point the break statement will exit out of the loop. This can be ...

    Solution Summary

    This solution explains why using "break" and "continue" is a bad idea. This is illustrated using a small bit of Java code.

    $2.19