Fill values in a vector and ask position and values

Asked

Viewed 1,608 times

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?

  • Could you clarify a little what you meant by your doubt? You have already successfully filled a vector of 10 positions, what else you need to do?

  • I want the user to enter the position value and its value Math

  • The difference then is simply the fact that the current code does not ask the position, only the value, correct?

  • Right, soh miss it

  • More questions came to me :) is that I thought your program would be a little strange the way you spoke, because you will have to deal with several situations that may cause a failure in the execution of your program, for example: how you intend to treat cases where users type a value outside the range of indexes that the vector has, example: its vector goes from 0 to 9, hence the user type 10, or worse, it type Z? What if the user repeats the value of an index he already reported? And if he doesn’t want to fill out the 10, can he stop? What do you expect the program to do in such cases?

  • Hi, Anderson, welcome to [en.so]. When someone asks for clarification, click [Dit] and update the post with new information. Then just let me know @, @fulano, atualizei a pergunta. From what I’ve seen of your answers too, I suggest reading the little guides [Answer] and [Ask]. Good luck!

Show 1 more comment

1 answer

1

The following solution uses two types of loop:

  • the do...while for the user to select the position of the vector he wants to fill and then fill this value
  • the 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]);
    }
  }
}
  • 2

    Welcome to Stackoverflow. It would be interesting to explain the code snippets of your solution.

  • Thank you @Renang. The above solution uses 2 types of loop: 1st. the of...while for the user to select the position of the vector he wants to fill and then filling this value 2º. o for "printa" the populated vector.

Browser other questions tagged

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