Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If-else should not have break?

So my professor mentioned that a break in an if/if-else statement is "bad" code. What exactly does she mean by that? Also how am I able to fix my code that I currently have written, because it does work the way I want it to, it's just now I need to get ride of the break statement.

    int sumOne = 1;
    int sumTwo = 1;
    int sumOneTotal = 0;
    int sumTwoTotal = 0;
    while(sumOne > 0 || sumTwo > 0){
        System.out.print("Enter a number to add to first sum: ");
        //The user enters in a value for the first sum.
        sumOne = input.nextInt();

        /**
         * We use an if-else statment to ensure sumOne is never less than or equal to 0.
         * If it does it ends the program immediately and totals the sums.
         * This is because we only want the user to enter in positive numbers.
         */
        if (sumOne <= 0){
            break;
        }else{
            sumOneTotal = sumOneTotal + sumOne;
        }

        System.out.print("Enter a number to add to second sum: ");
        //The user enters in a value for the second sum.
        sumTwo = input.nextInt();

        /**
         * We use an if-else statment to ensure sumTwo is never less than or equal to 0. 
         * If it does it ends the program immediately and totals the sums.
         * This is because we only want the user to enter in positive numbers.
         */
        if (sumTwo <= 0){
            break;
        }else{
            sumTwoTotal = sumTwoTotal + sumTwo;
        }
    }
    //We print out the total of sumOneTotal and sumTwoTotal.
    System.out.printf("%1s%1d%12s%1s%1d", "First sum: ", sumOneTotal, " ", "Second sum: ", sumTwoTotal);

Essentially I want the user to enter ANY positive number and that number is added to the first or second sum. Once the user enters any number <= 0 I want the program to stop immediately. The issue that I keep having when I tinker with the code is that the code keeps running through. Meaning if I have the user enter in 0 to be added to the first sum, the code still asks the user to enter in a number for the second sum. I need it to stop right away and not continue. Any help would be a great help! I am using Java.

EDIT!!! So let's say hypothetically I want to make a program that does the exact same thing I am doing now just with no break statement. How would I do so? A few rules. The most outer statement must be a "while" loop. The inner workings of it can be anything. I also need the machine to print out "Enter a number to add to first sum:" and "Enter a number to add to second sum:" alternating. So if I entered in 1,2,3,4. The first sum would be 4 and the second sum would be 6. Last rule is that it can not contain any break statements!

like image 756
Dylan Kelemen Avatar asked Oct 20 '16 20:10

Dylan Kelemen


3 Answers

This is a throwback to when structured programming was a new thing, back when goto statements and the like were everywhere. In theory, Ideally, you should never have to use breaks/continues, and only have a single point of return. In reality, doing so can make your job a lot harder by making programs harder to write, harder to read, and take up more computing resources. Multiple returns, continues and breaks are middle men between truly structured programming and spaghetti code. Used properly, there is nothing wrong with them.

Generally, I've found that they will only obscure your code if you're already using bad practices that make your code hard to read (For example, writing huge blocks of logic without breaking it up, tightly coupling objects etc).

If you're interested, here is a link to an interesting perspective on why NOT to use them. And here is a perspective on why they are benefical.

Many others have already answered with code, but here is my shot :)

public class Main {
    public static void main(String args[]) {
        int sumOne = 1;
        int sumTwo = 1;
        int sumOneTotal = 0;
        int sumTwoTotal = 0;
        Scanner input = new Scanner(System.in);
        while(sumOne > 0 || sumTwo > 0){
            System.out.print("Enter a number to add to first sum: ");
            sumOne = input.nextInt();
            if (is_positive(sumOne)){
                sumOneTotal = sum_numbers(sumOneTotal, sumOne);
                System.out.print("Enter a number to add to second sum: ");
                sumTwo = input.nextInt();
                if(is_positive(sumTwo)){
                    sumTwoTotal = sum_numbers(sumTwoTotal, sumTwo);
                }
            }
        }
        System.out.printf("%1s%1d%12s%1s%1d", "First sum: ", sumOneTotal, " ", "Second sum: ", sumTwoTotal);
        return;
    }
    public static int sum_numbers(int x, int y){
        int total = x + y;
        return total;
    }
    public static boolean is_positive(int x){
        boolean is_pos = true;
        if(x < 0){
            is_pos = false;
        }
        return is_pos;
    }
}

I'd say it's now harder to read. The more to the right my code starts to gravitate, the more I feel sorry for who needs to maintain it.. of course, I could remove a level or two of indentation by wrapping (more) bits in methods. Then it becomes easier to read, but there's a point where black-boxing every tiny bit of logic just seems redundant...

like image 185
ZombieTfk Avatar answered Oct 08 '22 06:10

ZombieTfk


If you draw the flowchart of your code you can see it exits a bucle in the middle of it, which isn't right, the right way is for it to exit when evaluated on the while, also when someone is reading your code they should expect the bucle is left when evaluated false on the while not in a random if inside the while block, I took your code and made some fixes to make it work as expected but I'm not sure if that's what your teacher expects.

    int sumOne = 1;
    int sumTwo = 1;
    int sumOneTotal = 0;
    int sumTwoTotal = 0;
    while (sumOne > 0 && sumTwo > 0) {
        System.out.print("Enter a number to add to first sum: ");
        // The user enters in a value for the first sum.
        sumOne = input.nextInt();

        /**
         * We use an if-else statment to ensure sumOne is never less than or
         * equal to 0. If it does it ends the program immediately and totals
         * the sums. This is because we only want the user to enter in
         * positive numbers.
         */
        if (sumOne > 0) {
            sumOneTotal = sumOneTotal + sumOne;
            System.out.print("Enter a number to add to second sum: ");
            // The user enters in a value for the second sum.
            sumTwo = input.nextInt();

            /**
             * We use an if-else statment to ensure sumTwo is never less
             * than or equal to 0. If it does it ends the program
             * immediately and totals the sums. This is because we only want
             * the user to enter in positive numbers.
             */
            if (sumTwo > 0) {
                sumTwoTotal = sumTwoTotal + sumTwo;
            }
        }
    }
like image 36
pescamillam Avatar answered Oct 08 '22 05:10

pescamillam


Much cleaner, no breaks.

int candidate  = 0;
int [] sums = {0,0};
int index = 1;

System.out.print("Enter a number to add to first sum: ");

while((candidate = input.nextInt()) > 0){
    sums[index] = sums[index] + candidate;
    index = (index + 1)%2;

    System.out.print("Enter a number to add to " + ((index == 0) ? "first":"second" ) + " sum: ");
    }
//We print out the totals.
System.out.printf("%1s%1d%12s%1s%1d", "First sum: ", sums[0], " ", "Second sum: ", sums[1]);

That isn't to say you should always avoid breaks, but in this case you can avoid it to make your code shorter, less redundant.

like image 1
Carlos Bribiescas Avatar answered Oct 08 '22 04:10

Carlos Bribiescas