Fill values in a vector and ask for position and values

0
public class teste4 {
 Scanner op = new Scanner(System.in);
  int[] vetor = new int[10];{
  for (int i = 0; i < vetor.length; i++) {
        System.out.println("Digite o valor da posição " + i);
        vetor[i] = op.nextInt();

    }

  }

How to proceed?

    
asked by anonymous 18.09.2014 / 01:11

1 answer

1

The following solution uses two loop types:

  • the do...while for the user to select the position of the vector that he wants to fill and then filling this value
  • o for "printa" the populated vector.
import java.util.Scanner;

public class teste4 {
  public static void main(String[] args) {
    Scanner op = new Scanner(System.in);
    int[] vetor = new int[10];
    int i;

    do {
      int y;

      System.out.println("Digite a posição do vetor de 0 a 9 (-1 para sair):");
      i = op.nextInt();

      if (i != -1) {
        System.out.println("Informe o valor da posição " + i + ":");
        y = op.nextInt();

        vetor[i] = y;
      }
    } while (i > -1);

    for (i = 0; i < vetor.length; i++) {
      System.out.println("Valor da posição: " + i + ": " + vetor[i]);
    }
  }
}
    
18.09.2014 / 06:10