There’s a ;
where you shouldn’t be there, you’re shutting down the for
doing nothing (it closes in the ;
without having a block to execute), there opens a single block isolated, without belonging to the for
where it obviously takes the value i
last increased in the for
and it is worth 2, the value that indicates that you should close the loop, then you will access the index using this variable and falls out of the range. This is how it works:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] vet = new int[2];
for (int i = 0; i < 2; i++) {
System.out.println("Digite um numero");
vet[i] = sc.nextInt();
}
for (int i = 0; i < 2; i++) System.out.println(vet[i]);
}
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Note the detail that I declared the variable within the loop. Some people find it silly to do this, others make the statement out because they have learned wrong that it is best to do it before (it is best to do it as close to its use, with the least possible scope), and if you had made the statement on for
would make a more obvious mistake in that situation and would already happen in the compilation which is much better. It has recommendations that seem freshness, but they exist because they are useful.
vlw, thank you very much, I understood where the mistake was
– Rafael Lopes