1

I need to take characters from a text file and store them row major order in a 2D character array that is 20 by 45. I will then need to print out the stored characters column major. This needs to work with any size text file. This code is as far as I have gotten and I haven't been able to print it out column major yet.

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();
        }

    }

}

This code prints it out and then I get an error message.

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)
GBlodgett
  • 12,704
  • 4
  • 31
  • 45
TBink
  • 49
  • 5

2 Answers2

0

/* I think you are trying below: Instead of String you might wanna use stringbuilder or stringbuffer */

  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();
        }

    }
0

It might be that st.length is not long enough.

if (st != null && st.length() < offset) {
    st = br.readLine();
}
Jeremy Walters
  • 2,081
  • 16
  • 28