Prevent repetition of an element in a part of the code

Asked

Viewed 44 times

0

I have the following exercise that asks me to define an interval and sum all the even values of that interval showing which numbers are summed between them, like:

Min=10
Max=15

10+12+14=36.

However. the output I get is:

10+12+14+=36.

That is.I have an extra "+". I leave the code here:

    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); 

1 answer

1

First, you can combine the two do-whiles in a single using one || to match the conditions.

Second, not to confuse, instead of increasing min and summing into a variable i, let min unchanged and change the name of i for soma. Also declare a variable valor which corresponds to the value to be summed.

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

Bedroom, to fix this problem, instead of putting the + after the number and try not to put after the last one, it is easier to put before the number and do not try to put before the first one. The reason for this is that it is easier to know which is the first one than the last one. 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);
  • 1

    I prefer String sinal = "";...soma+=valor;sysout(sinal+valor);sinal="+" =)

  • 1

    @Mari It may also be.

Browser other questions tagged

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