如何从2d阵列复制1列并将其放入1d阵列

时间:2019-11-29 05:52:02

标签: java arrays string

我正在尝试将2d数组中的1列的名称放入名为name的String 1d数组中,但是它会重复5次。我似乎无法使它出现一次,关于如何解决此问题的任何想法?

// a 2d array list obtained from a file
Monica - 23
Mike - 24
Adam - 44
Mark - 78
Beth - 78
public static String [] sortName (String [] [] data) {

        // Sort the names and put it in a 1d array

        //[rows] [col]

        String [] names = new String [5];
        for (int n = 0; n < names.length; n++) {
            for (int q = 0; q < 5; q++ ) {
            names [n] = data[q] [0];

                // Print to see if it works
              System.out.println(names[n]);
                    }
              }

        return names;
    }
//output
Monica
Mike
Adam
Mark
Beth
Monica
Mike
Adam
Mark
Beth
Monica
Mike
Adam
Mark
Beth
Monica
Mike
Adam
Mark
Beth
Monica
Mike
Adam
Mark
Beth

1 个答案:

答案 0 :(得分:0)

您的名称数组的长度为5,因此它将在您的第一个循环中循环5次。您需要将其更改为data.length。

您需要将其更改为此:

public static String[] sortName(String[][] data)
{
    // Sort the names and put it in a 1d array
    // [rows] [col]

    String[] names = new String[data.length]; // <------ This needs to be the data.length and not 5.

    for (int n = 0; n < names.length; n++)
    {
        for (int q = 0; q < data.length; q++)
        {
            names[n] = data[q][0];

            // Print to see if it works
            System.out.println(names[n]);
        }
    }

    return names;
}