JAVA - Split and Arrays

Asked

Viewed 199 times

0

Hello,

I need to read several strings, divide them into parts and allocate them to arrays.

The problem is that my code even stores the pieces of the string in the variables, but I need to read several pieces, so I need to transform these attributes into arrays.

I have four attributes: Type, which takes char, Color, recendo String, and X and Y which take int.

An example entry for this code is: C White 2 2.

public void inserirPeças() throws IOException {

    for (int i = 0; i < num; i++) {

        System.out.println("Insira as peças: ");
        String str = input.readLine(); // le a linha inteira
        String[] tokens = str.split(" "); // pega os tokens separadamente

        tipo = tokens[0].charAt(0); // le o tipo
        cor = tokens[1]; // le a cor
        x = Integer.parseInt(tokens[2]); // x
        y = Integer.parseInt(tokens[3]); // y
    }   
}

Thank you!

1 answer

0


To declare attributes as arrays use these instructions:

char[] tipo;
String[] cor;
int[] x;
int[] y;

And when you know the size of them (assuming num), initialize them:

public void inserirPeças() throws IOException {

    // Inicializando as arrays
    tipo = new char[num];
    cor = new String[num];
    x = new int[num];
    y = new int[num];

    for (int i = 0; i < num; i++) {
        System.out.println("Insira as peças: ");
        String str = input.readLine();
        String[] tokens = str.split(" ");

        // Não se esqueça do índice das arrays
        tipo[i] = tokens[0].charAt(0);
        cor[i] = tokens[1];
        x[i] = Integer.parseInt(tokens[2]);
        y[i] = Integer.parseInt(tokens[3]);
    }   
}

Browser other questions tagged

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