开发者

Quick help with ArrayIndexOutOfBoundsException on 2d array

In the code below the for loop is giving an "java.lang.ArrayIndexOutOfBoundsException: 2" error, i can not see why, if i change "emailArray[i][2] = messageContent[i]" to "emailArray[i][1] = messageContent[i]" it works, is my layout for the 2d array wrong?

public String[][] fetchEmails() throws Exception {

        String[][] emailArray;

        Properties props = new Properties();

        Session session = Session.getDefaultInstance(props, null);

        Store store = session.getStore("imaps");

        store.connect("pop.gmail.com", "******@googlemail.com", "********");
        System.out.println(store);


        Folder folder = store.getFolder("Inbox");

        folder.open(Folder.READ_ONLY);

        int howmuch = folder.getMessageCount();
        Message message[] = folder.getMessages();

        String[] messageContent = new String[message.length];

        messageContent = convertContent(message);

        emailArray = new 开发者_运维问答String[message.length][2];        

        for (int i = 0; i<message.length; i++){
            emailArray[i][0] = message[i].getFrom()[0].toString();
            emailArray[i][1] = message[i].getSubject().toString();
            emailArray[i][2] = messageContent[i];
        }

    folder.close(false);
    store.close();

    return emailArray;
}


Here you define a 2D array with dimensions message.length by 2:

emailArray = new String[message.length][2];

Here you try to access the i-th row's 3rd column:

emailArray[i][2] = messageContent[i];

But there is no 3rd column, you've defined it to have 2 columns.

Arrays are zero-indexed in Java, this means you access the 1st element of an array using 0, the 2nd element as 1 and so on. Basically, if you want 3 elements, then you need to define emailArray as:

emailArray = new String[message.length][3];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜