ArrayOutOfBoundException 二维数组 Java

问题描述 投票:0回答:1

我有一个名为“simpleText”的 String 类型的 ArrayList,它根据用户的不同保存不同数量的句子。我有另一个名为“eachSentence”的 char 类型数组,它是二维的,用于存储每个句子的每个字符。第一行是第一句话,依此类推。第一次迭代后,我得到 ArrayOutOfBoundException。

ArrayList<String> simpleText = new ArrayList<String>();
char[][] eachSentence = new char[simpleText.size()][];
public void setStringArray(){
        String sentence;
        for (int i = 0; i < simpleText.size(); i++){
                for(int j = 0; j < simpleText.get(i).length(); j++){
                    
                    sentence = simpleText.get(i);
                    eachSentence[i][j] = sentence.charAt(j);
                }
        }
          
    }

我调试了代码,在下一次迭代之前看起来一切正常。调试器告诉我

eachSentence[i][j] = sentence.charAt(j);
是问题所在。请帮忙。

java string charat
1个回答
0
投票

在Java中,二维数组可以被认为是数组的数组,即数组中的每个元素都是一个数组。因此,二维数组可以是锯齿状数组,即每个元素可以是不同大小的数组。

在您问题的代码中,您需要显式地为数组的第二个维度赋值

eachSentence
但事实并非如此。由于每个句子可以有不同的长度,我建议为每个句子创建一个新数组并将该新数组添加到
eachSentence

import java.util.ArrayList;
import java.util.List;

public class Sentences {

    public static void main(String[] args) {
        List<String> simpleText = new ArrayList<String>();
        simpleText.add("This is the first sentence.");
        simpleText.add("This sentence is the second sentence.");
        simpleText.add("This will be the last sentence.");
        char[][] eachSentence = new char[simpleText.size()][];
        for (int i = 0; i < simpleText.size(); i++) {
            String aSentence = simpleText.get(i);
            int len = aSentence.length();
            char[] letters = new char[len];
            for (int j = 0; j < len; j++) {
                letters[j] = aSentence.charAt(j);
            }
            eachSentence[i] = letters;
        }
        for (int i = 0; i < eachSentence.length; i++) {
            for (int j = 0; j < eachSentence[i].length; j++) {
                System.out.print(eachSentence[i][j] + " ");
            }
            System.out.println();
        }
    }
}

运行上述代码会产生以下输出:

T h i s   i s   t h e   f i r s t   s e n t e n c e . 
T h i s   s e n t e n c e   i s   t h e   s e c o n d   s e n t e n c e . 
T h i s   w i l l   b e   t h e   l a s t   s e n t e n c e .
© www.soinside.com 2019 - 2024. All rights reserved.