Error reading a long number in java

Asked

Viewed 193 times

-1

I am reading a vector in java and make the sum of all the elements but this saying that 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];
    }
 }

}
  • when the error occurs?

  • netbeans itself mimics an alert

  • Why not direct sum? Need to store in vector even?

1 answer

3


Arrays should be indexed with int, cannot be with long. Make the variable i was int and this build problem will be solved. The best place to declare the variable i is in the loop itself for. 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.

  • Thank you Victor

  • 1

    @rafaelmarques , if solved your problem, do not forget to mark the answer as accepted by clicking on . I, for example, did not know the question that I can not index by long, I thought you did cast automatic, so it was very useful to me. And look, it’s already been 5 years dealing professionally with Java and I ignored this fact

  • 1

    @Jefferson Quesado, pronto marquei, is living and learning

Browser other questions tagged

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