我有这样的输入ArrayList<String>:
cat eats mouse
mouse eats cheese
cheese is tasty
(应该忽略空白行,因为我将从文件中读取此输入)
我想将它转换为具有尺寸的2-D String数组[no. of elements in ArrayList][3].
没有.3是固定的,即每个句子将有3个单词.像这样:
"cat"    "eats" "mouse"
"mouse"  "eats" "cheese"
"cheese" "is"   "tasty"
这是我尝试过的:
    public static int processData(ArrayList<String> array)
    {
        String str[]=new String[array.size()];
        array.toArray(str);
        String str1[][]=new String[str.length][5];
        for(int i=0;i<str.length;i++)
        {
                str1[i][]=str.split("\\s+");    //i want to do something like this, but this is showing errors.
        }
        return 0; //this is temporary, I will be modifying it
    }
告诉我,如果我不清楚.
你很接近。在 Java 中,不能使用空括号将新元素放在数组末尾[]。下面的代码就完成了这个事情。请注意,第二个数组中的元素数量限制为 5。因此,在前 5 个单词之后,该行的其余部分将被忽略。null如果行较短,则数组末尾会有s。
public static int processData(ArrayList<String> array) {
    String[] str = new String[array.size()];
    array.toArray(str);
    String[][] str1 = new String[str.length][3];
    for(int i=0; i < str.length; i++) {
        String[] parts = str[i].split("\\s+");
        for(int j = 0; j < parts.length || j < 3; j++) {
            str1[i][j] = parts[j];
        }
    }
    // do something next
}