Prevent the repetition of an element in a part of the code

0

I have the following exercise that asks me to define a range and sum all the even values of that range showing which numbers added together, of the sort:

  

Min = 10
  Max = 15

     

10 + 12 + 14 = 36.

However. the output I get is:

  

10 + 12 + 14 + = 36.

I mean, I have an "+" more. I leave here the code:

    int min = 0;
    int max = 0;
    do{  
        do{
            System.out.println("Insira um valor min:");
            min = scanner.nextInt();
            System.out.println("Insira um valor max:");
            max = scanner.nextInt();
        }while (min<0 || max >100);
    }while(min>max);
    int i = 0;
    while((min<max))
    {            
        if(min % 2==0)
        {
            i+=min;
            System . out . print(min + "+");
        }min++;
    }
    System . out . print("=" + i); 
    
asked by anonymous 30.10.2017 / 15:09

1 answer

1

First, you can combine the two do-while s into one by using || to match the conditions.

Second, not to confuse, instead of incrementing min and summing it in a variable i , leave min unchanged and rename i to soma . Also declare a variable valor that corresponds to the value to be summed.

Third, using a for is much more practical than a while in this case.

Fourth, to fix this problem, instead of putting + after the number and try not to put after the last, it is easier to put before the number and not try to put before the first. The reason for this is that it is easier to know which is the first than the last. You can use a Boolean variable to control this.

    int min = 0;
    int max = 0;
    do {
        System.out.println("Insira um valor min:");
        min = scanner.nextInt();
        System.out.println("Insira um valor max:");
        max = scanner.nextInt();
    } while (min < 0 || max > 100 || min > max);

    boolean jaFoiOPrimeiro = false;
    int soma = 0;
    for (valor = min; valor <= max; valor++) {
        if (valor % 2 == 0) {
            soma += valor;
            if (jaFoiOPrimeiro) {
                System.out.print("+");
            } else {
                jaFoiOPrimeiro = true;
            }
            System.out.print(valor);
        }
    }
    System.out.print("=" + soma);
    
30.10.2017 / 15:30