Error reading a long number in java

-1

I'm reading a vector in java and making the sum of all elements but this is saying that they are incompatible type, how to solve

My code

package capitulo2;

import java.util.Scanner;

public class Capitulo2 {

public static void main(String[] args) {
    Scanner teclado = new Scanner(System.in);
    long i, tam,soma=0;
    tam = teclado.nextLong();
    long [] vetor = new long[10000002];
    for (i = 0; i < tam; i++) {
        vetor[i] = teclado.nextLong();
        soma += vetor[i];
    }
 }

}
    
asked by anonymous 01.07.2018 / 23:18

1 answer

3

Arrays should be indexed with int , can not be long . Make the variable i be int and this compile problem will be solved. The best place to declare the variable i is in the for loop itself. For example:

import java.util.Scanner;

class Capitulo2 {

    public static void main(String[] args) {
        Scanner teclado = new Scanner(System.in);
        long soma = 0;
        long tam = teclado.nextLong();
        long[] vetor = new long[10000002];
        for (int i = 0; i < tam; i++) {
            vetor[i] = teclado.nextLong();
            soma += vetor[i];
        }
    }
}

See here working on ideone.

    
01.07.2018 / 23:26