I want to save 3 numbers and then print on the screen

Asked

Viewed 65 times

-2

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] vet = new int[2];
        int i;

        for (i=0; i<2; i++); {
            System.out.println("Digite um numero");
            vet[i] = sc.nextInt();

        }   
         for (i=0; i<2; i++);{
             System.out.println(vet[i]);
         }

            sc.close();

    }     
}

Gives an error in the line vet[i] = sc.nextInt();

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
  at Main.main(Main.java:12)

1 answer

1


There’s a ; where you shouldn’t be there, you’re shutting down the fordoing 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

Browser other questions tagged

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