Having difficulties creating a program that reading and writing 2D arrays to/from .txt files in Java

StackOverflow https://stackoverflow.com/questions/19662210

  •  01-07-2022
  •  | 
  •  

Question

For a homework assignment, I need to create a class that that can read and write Byte arrays to/from a file. I have successfully created classes that can read and write CSV and text, however I am having some difficulty, when it comes to arrays.

When I run the 'readByte' method (see below) I do not get compiler errors , instead, I can not get the contents of the file to print. Instead the console just displays "File Read", demonstrating that it has successfully processed the nested for loop. I have studied various resources yet I can not find the solution. I am sure it is a simple mistake somewhere, any advice on how I can resolve this will be greatly appreciated.

The contents of the file I am trying to read is also below.

A second question (I thought it would be best to put both questions in one post), in my 'writeByte' method (the user enters values into a 2D array which is then printed in a .txt file), allows me to enter two values before I get the follow error message:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at com.gc01.FileManager.ByteManager.writeByte(ByteManager.java:93)
at com.gc01.FileManager.ByteManager.main(ByteManager.java:111)

I am sure its something to do with how the for the loop collects the user input, but I can't work out how to correct it. Ideally the file would look similar to the file being read by the 'readByte' method.

I understand this a long question, but I have run into a brick wall and all help would be greatly appreciated!


File Contents (separated by tab)


1     10
2     11
3     12
4     13

public class ByteManager {

public String getByteFile(){
    Scanner sc = new Scanner (System.in);
    System.out.println("Please enter the file directory of the chosen txt file?");
    System.out.println("For Example: /Users/UserName/Downloads/FileName.txt");
    ///Users/ReeceAkhtar/Desktop/FileName.txt
    final String fileName = sc.nextLine();
    System.out.println("How many columns are in the file?");
    final int columns = sc.nextInt();
    System.out.println("How many rows are in the file?");
    final int rows = sc.nextInt();
    return fileName;
    }



public void readByte(final String fileName, int rows,int columns){

BufferedReader br = null;

String[] line;
String splitBy =  "\t";
int [][] data = new int[rows] [columns];


try {
    br = new BufferedReader(new FileReader(fileName));  
        for (int i = 0; i < rows; i++){
            line = br.toString().split(splitBy);
            //data[i] [0] = Integer.parseInt(line[i]);
            for (int j = 0; j < columns; j++){
                data[i] [j] = Integer.parseInt(line[j]);
                System.out.println(data[i][j]);
            }
        }       
    } catch (FileNotFoundException e){
        e.printStackTrace();
    } catch (IOException e) {   
        e.printStackTrace();  
    } finally {  
        if (br != null) {  
        try {  
        br.close();  
    } catch (IOException e) {  
        e.printStackTrace();  
    }
        }
    }
    System.out.println("*****File Read*****");
}


public String chooseFileOutput(){
    Scanner sc = new Scanner (System.in);
    System.out.println("Please enter the file directory for the output of the chosen file");
    System.out.println("For Example: /Users/UserName/Downloads/FileName.txt");
    ///Users/ReeceAkhtar/Desktop/GeoIPCountryWhois.csv
    final String fileNameOUT = sc.nextLine();
    return fileNameOUT;
    }

public void writeByte(final String fileNameOUT){
    Scanner input = new Scanner (System.in);
    FileOutput createData = new FileOutput (fileNameOUT);
    System.out.println("How many rows?");
    int rowsOut = input.nextInt();
    System.out.println("How many columns?");
    int columnsOut = input.nextInt();


    System.out.println("Please enter data.");

        int newDataR = 0;
        int newDataC = 0;
        int [] [] data = new int [rowsOut] [columnsOut];    


        for (int i = 0; i < rowsOut; i++){
            createData.writeInteger(newDataR = input.nextInt());
            System.out.print("\t");
            for (int j = 0; j < columnsOut; i++){
                createData.writeInteger(newDataC = input.nextInt());
                data[i] [j] = data[newDataR] [newDataC];
                System.out.print("\t");
            } 
        }   
        createData.close();

}

public static void main(String[] args) {
    Scanner in = new Scanner (System.in);
    final ByteManager object = new ByteManager ();

    System.out.println("1 for Read File, 2 for Write file");
    String choice = in.nextLine();
    if("1".equals(choice)){
        object.readByte(object.getByteFile(), 0, 0);
    } else if ("2".equals(choice)){
        object.writeByte(object.chooseFileOutput());
    } else{
        System.out.println("Goodbye!");
        System.exit(0);
    }
}
}
Was it helpful?

Solution

For your first question (about being unable to read):

In the main method, the following line:

object.readByte(object.getByteFile(), 0, 0);

Provides 0 and 0 for the number of rows and columns to be read from the text file. The method getByteFile() does prompt the user for a number of rows and columns, however it does not return this amount and does nothing with those numbers. You must prompt the user for the number of rows and columns and put those as the second and third arguments of the readByte method in main.

Also, in general, I wonder why you bother to create the object int[][] data in both your readByte and writeByte methods. They are void methods, so you don't return the int[][], or do anything meaningful with it. Do you intend to use this object later?

OTHER TIPS

"Line 93 is: 'data[i] [j] = data[newDataR] [newDataC];"

OK that's your problem. I think what you mean to do is the following:

data[i][j] = newDataC;

A multidimensional array is just an array of arrays. When you have an access like this:

data[i][j]

What that means is you are accessing element #j of array #i.

data[][] is an array of int arrays, data[i] is an array of ints and data[i][j] is an int element in data[i].

So what I would recommend is reviewing how multidimensional arrays work and then generally reviewing your code to look for stuff like this:

createData.writeInteger(newDataR = input.nextInt());

Which basically seems nonsensical. Not meant as a negative comment, this line just doesn't make sense in the context of multidimensional arrays because only the "columns" hold int elements.

For your exception: I wasn't sure my comment was clear, so I'll try here. You have:

for (int i = 0; i < rowsOut; i++){
    createData.writeInteger(newDataR = input.nextInt());
    System.out.print("\t");
    for (int j = 0; j < columnsOut; i++){  //do you mean to increment j here?
        createData.writeInteger(newDataC = input.nextInt());
        data[i] [j] = data[newDataR] [newDataC];
        System.out.print("\t");
    } 
} 

On your second for loop, your are incrementing i, instead of j. You're incrementing it twice, so you'll go 0,2,4... So you are almost certainly going to exceed that dimension of your array. As Radiodef said, I think you would benefit from reading up on multi-dimensional arrays.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top