Fill a vector using useDelimiter in Java

Asked

Viewed 12 times

-1

Hello, I’m wanting to fill a vector using the useDelimiter of Java. For now I only know how to fill a vector this way using for:

for (int i = 0; i < vet.length; i++) {
            System.out.print("Digite um número: ");
            vet[i] = s.nextInt();
            soma += vet[i];
        }

in this precise exercise calculate the average of the items within the vector.

The user input would be this:

3;9;4;5;8;0;1;8;5;1;3;2;6;4;7;

Researching I found the useDelimiter as an alternative, but I still don’t understand how it could work in this scenario. If anyone can help me, I am very grateful!

1 answer

0

If you want to read the string at once and separate the values do not need to use the useDelimiter, can use the split to separate the string in an array.

In the example below I do this, generating a string array (string to string) and then I do a for to read the values and add and/or create an int array:

// aqui pode usar o Scanner para ler a string, nesse exemplo, deixei fixo
String numsString = "3;9;4;5;8;0;1;8;5;1;3;2;6;4;7";
// converte para um array de string, usando o separador ";"
String[] numsStringArray = numsString.split(";");

int[] numsIntArray = new int[numsStringArray.length];
int soma = 0;
// converte para um array de int
// poderia apenas somar, deixei o exemplo mais generico a quem possa interessar
for (int i = 0; i < numsIntArray.length; i++)
{
  numsIntArray[i] = Integer.parseInt(numsStringArray[i]);
  soma += numsIntArray[i];
}

System.out.println(soma);

You can see it working here: https://www.mycompiler.io/view/AERwSIJ

Browser other questions tagged

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