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);
}
}
}
Thanks friend, I used the second logic, incrementing two by two and solved the problem!
– Matheus Portugal