Skip to content
Advertisement

BufferedReader saving sentence, String array, then 2D int array

I have a .txt file that contains text that I would like to save part of it in a String, part of it in a String array, and then the last part in a 2D int array, and am faced with two issues:

  1. How to read and save both of the arrays when their size is not known ahead of time?
  2. 2D array is not reading/saving properly

Here is the text file for reference:

JavaScript

Here is part of my method that is supposed to read and save the three data types:

JavaScript

How would I “grab” the size of the arrays by reading the text file, so that when I initialize both arrays, I have the proper sizes? Any help would be greatly appreciated!

Advertisement

Answer

Instead of trying to achieve everything in a single pass we can pass through the file twice and obtain a neater code.

It will consume double time of course but it is going to help you understand how you could break bigger problems into smaller ones and deal with them one by one.

Here are the steps:

  1. Determine size of stringArr and intArr in first pass
  2. Fill value in respective array in second pass

If you are wondering how no of columns for int2DArr is determine. Simply we don’t do it our self. We use the concept of Jagged Arrays

Read more here How do I create a jagged 2d array in Java?

JavaScript

Note: In single pass this could be accomplished with the help of ArrayList and later transfer everything into respective array.

Update: After understanding the constraints for your problem here is another version

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement