Search code examples
javaarraysstringarraylistjoptionpane

Correct way with splitting and storing an array?


I recently asked a question on here and learned how to split my array up. Now I'm messing around with storing the separated array. I know this code is probably very wrong since I was just trying to figure it out myself. The intended purpose of this code was to see if after splitting the array(which can be up to 10 names and 10 degrees) it was possible to store the inputs. The purpose of the System.out was to see if they were storing. I keep getting an error that the symbol result could not be found. Any help is appreciated.

import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.JOptionPane;

public class PeerTutoring
{
public static void main(String[] args)
{
    ArrayList<String> list = new ArrayList<String>();

    int a = 0;
    int b = 1;
    int c = 0;
    int d = 1;

    for(int i=0;i<20;i++) {
        String line;
        line = JOptionPane.showInputDialog("Please enter tutor name and their highest earned degree.");
        String[] result = line.split("\\s+");
        String[] name = new result[a];
        String[] degree = new result[b];
        a++;
        b++;
        System.out.println(name[c]);
        System.out.println(degree[d]);
        c++;
        d++;
}
}

Solution

  • new result[a] is ...sort of... syntax for initializing an array that holds result instances, with size a. But that's not what you mean – you don't have a class called result, and you just want to get elements out of the array named result. Right?

    Just remove the new, and the extra [] in the name declaration.

    String name = result[a];
    String degree = result[b];
    

    I think you would find the Java Tutorial: Arrays extremely useful.


    Hint for future use: if you want to print an array, you don't need to do all this legwork. Just use Arrays#toString().