Algorithm that reads three numbers and displays the result of the sum of the first two and multiplied by the third

0

public class Exercicio2 {

@SuppressWarnings("unused")
public static void main(String[] args) {
    Scanner entrada = new Scanner(System.in);
    int i = 0;
    int[] soma = new int[3];
    int numero1, numero2 = 0;
    int total = 0;
    while(i < 3){
        System.out.println("Informe um numero[" + i + "]");
        soma[i] = entrada.nextInt();
        soma[i] += soma[i];
        total = soma[i];
        i++;
    }
    System.out.println(total);
   }
 }
    
asked by anonymous 05.09.2017 / 10:16

2 answers

1

In this line

soma[i] += soma[i];

You are multiplying what was entered by 2. That is, if you entered 2 at index 0 you are doing sum [0] = sum [0] + sum [0]

What you should do is a cycle where you only record the entries:

for(int i = 0; i < 3; i++)
{
    System.out.println("Informe um numero[" + i + "]");
    soma[i] = entrada.nextInt();
}

And then you do the following:

total = (soma[0] + soma[1]) * soma[2];

Final code:

public class Exercicio2 {

@SuppressWarnings("unused")
public static void main(String[] args) {
    Scanner entrada = new Scanner(System.in);
    int[] soma = new int[3];
    int total = 0;
    for(int i = 0; i < 3; i++)
    {
        System.out.println("Informe um numero[" + i + "]");
        soma[i] = entrada.nextInt();
    }
    total = (soma[0] + soma[1]) * soma[2];
    System.out.println(total);
   }
 }
    
05.09.2017 / 10:50
0

You only have to check the steps performed by while , received the first number, increment the variable i , and contains the 1 value because you have already received the first and the second number, the sum, if it contains the value 2 is because it received the third one then does the multiplication.

public static void main(String []args){
        Scanner entrada = new Scanner(System.in);
        int i = 0;
        // Alterei o nome da variavel, soma para numeros.
        int[] numeros = new int[3];
        // Criei outra variavel int com nome soma.
        int soma = 0;
        // int numero1, numero2 = 0; -> Não tem utilidade
        int total = 0;
        while(i < 3){
            System.out.println("Informe um numero[" + i + "]");
            numeros[i] = entrada.nextInt();
            // Verifica se já recebeu o primeiro numero, então faz a soma do primeiro com o segundo
            if (i == 1) {
                soma = numeros[0] + numeros[1];
            }
            // Ultima etapa, multiplica pelo terceiro.
            if (i == 2) {
                total = soma * numeros[i];
            }
            i++;
        }
        System.out.println(total);
    }
    
05.09.2017 / 10:43