Method does not return correct value

-1

I have the following code:

public class Main {
    public static void Main (String[] args) {
        Metodo R = new Metodo();
        Scanner entrada = new Scanner(System.in);
        int[] valores = new int[10];
        int i = 0;
        while (i < valores.length) {
            System.out.println("Insira um número.");
            valores[i] = entrada.nextInt();
            i++;
        } System.out.println(R.somar(valores));
    }
}
public class Metodo {
    public int somar(int[] valores) {
        int soma = 0, i = 0;
        while (i < valores.length) {
            if (valores[i] % 2 == 0.5) {
                soma = soma + valores[i];
            }
            i++;
        }
        return soma;
    }
}

For some reason I do not know, it always returns 0, even putting only odd numbers, for example, if I only put the number 1 in all indexes of the array, it should return 10, but returns 0.

How can I resolve it?

    
asked by anonymous 06.04.2014 / 04:27

1 answer

4

One of the reasons is that in the somar(int[] valores) method there is an infinite loop. You are using i < valores.length as a condition, but forgot to i++ after if .

I did not understand the purpose of the program correctly, but it seems to me that it is to add the odd numbers of a vector. In this case, the valores[i] % 2 == 0.5 , comparison to integers will always result in false because the remainder of the division by 2 ( x % 2 ) is equal to 1 for odd or 0 for even. p>

So, if you want to add the odd ones:

    while (i < valores.length) {
        if (valores[i] % 2 == 1) {
            soma = soma + valores[i];
        }
        i++;
    }

And for the pairs:

    while (i < valores.length) {
        if (valores[i] % 2 == 0) {
            soma = soma + valores[i];
        }
        i++;
    }
    
06.04.2014 / 05:28