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]);
}
}
}
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?
– Math
I want the user to enter the position value and its value Math
– Anderson Mendes
The difference then is simply the fact that the current code does not ask the position, only the value, correct?
– Math
Right, soh miss it
– Anderson Mendes
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?– Math
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!– brasofilo