如何用文本文件中的字符填充二维字符数组

时间:2019-01-21 05:20:47

标签: java arrays multidimensional-array

我需要从文本文件中提取字符,并将它们的行专业顺序存储在2字符数组中,即20 x45。然后,我需要打印出存储的字符专业行。这需要使用任何大小的文本文件。据我所知,这段代码我还无法将其打印在专业栏上。

package myfirstjavaproject;

import java.io.*;
import java.util.Scanner;

public class temp {
    public static void main(String[] args)throws Exception{
        File file = new File ("test.txt");
        BufferedReader br = new BufferedReader(new FileReader(file)); 
        String st = br.readLine();  


        int row = 20, column = 45;
        int offset = 0;
        char[][] array = new char [row][column];
        for (int i = 0; i < row; i++) {
            for(int j = 0; j < column; j++) {
                array[i][j] = st.charAt(offset++);
                System.out.print(array[i][j]);
            }
            System.out.println();
        }

    }

}

此代码将其打印出来,然后出现错误消息。

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 55
    at java.lang.String.charAt(Unknown Source)
    at myfirstjavaproject.temp.main(temp.java:18)

2 个答案:

答案 0 :(得分:0)

/ *我想您正在尝试以下操作:您可能想使用stringbuilder或stringbuffer代替String     * /

  public static void main(String[] args)throws Exception{
        File file = new File ("test.txt");
        BufferedReader br = new BufferedReader(new FileReader(file)); 
        String st = br.readLine();  
        String s = null;
        while(br.read()!=-1)
        {
             s=s+br.readLine();
        }

        int row = 20, column = 45;
        int offset = 0;
        char[][] array = new char [row][column];
        for (int i = 0; i < row; i++) {
            for(int j = 0; j < column; j++) {
                array[i][j] = s.charAt(offset++);
                System.out.print(array[i][j]);
            }
            System.out.println();
        }

    }

答案 1 :(得分:0)

st.length可能不够长。

if (st != null && st.length() < offset) {
    st = br.readLine();
}