Java program to insert lower and upper bound and return the sum of even numbers from the range

Asked

Viewed 313 times

1

I’m having trouble getting this code to work properly. The goal is to sum all the even numbers of a given range (upper and lower limit), but is not returning the correct result using the for.

For example, if I insert: Lower Bound (ltinf) = 0 and Upper Bound (ltsup) = 5, the program returns the value 12 and not the sum 2+4 = 6.

Could someone shed some light on this problem?

package ps1ex3matheusportugal;
import javax.swing.JOptionPane;

public class PS1EX3MatheusPortugal {

    public static void main(String[] args) {

        int ltsup = Integer.parseInt(JOptionPane.showInputDialog("Insira o limite superior: "));
        int ltinf = Integer.parseInt(JOptionPane.showInputDialog("Insira o limite inferior: "));

        if (ltsup < ltinf){
            JOptionPane.showMessageDialog(null, "O valor do limite inferior deve ser menor que o limite superior");
        }
        else if (ltsup > ltinf){
            int cont, somapar = ltinf;
            for (cont = ltinf; cont <= ltsup; cont++){
                if (cont % 2 == 1){
                    cont++;
                    somapar = somapar + 2;
                }
                else{
                    for (cont = ltinf; cont <= ltsup; cont++){
                        somapar = somapar + 2;
                    }
                }
            }
            JOptionPane.showMessageDialog(null, "A soma de todos os números dentro do intervalo inserido é: " + somapar);
        }
    }

}

1 answer

1


for (cont = ltinf; cont <= ltsup; cont++){
    if (cont % 2 == 1){
        cont++;
        somapar = somapar + 2;
    }
    else{
        for (cont = ltinf; cont <= ltsup; cont++){
            somapar = somapar + 2;
        }
    }
}

This logic is confused, there’s even a go inside Else. I can’t even tell you how to fix it, what I can suggest is reworking the code.

int somapar = 0;
for (int cont = ltinf; cont <= ltsup; cont++) {
    if (cont % 2 == 0){
        somapar += cont;
    }
}

You can also increment the counter two by two, ensuring that the counter will always be even:

int somapar = 0;
if (ltinf % 2 != 0) {
    ltinf++;
}
for (int cont = ltinf; cont <= ltsup; cont += 2) {
    somapar += cont;
}
  • Thanks friend, I used the second logic, incrementing two by two and solved the problem!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.