Skip to content
Advertisement

How to auto create arrays

Hello! So there’s a problem.

We’re given a file.txt with a lot of numbers (let’s consider the amount is greater than 1000). On the first line we can see the amount of numbers. The next lines contain numbers (1 line = 1 number). So we need to write a code which will autofill arrays with all these numbers. We’re not allowed to fill one array with more than 100 elements, because it will destroy our PC (I’ve read it somewhere).

Example of the file.txt:

5
78
67
56
45
23

I don’t know how to auto create arrays depending on an amount of numbers we have.

I will be grateful for the help.

P. S. please don’t write and suggest very difficult constructions, I won’t understand them, because I am the beginner in programming 😀

Advertisement

Answer

  1. Read the first line and convert the result to a number that you store to count.
  2. Then add this line: int [] array = new int [count];
  3. Next setup a for loop: for( var i = 0; i < count; ++i ) and in this loop, you read the current line, convert the value to a number and store it to array [i].

Is this explanation simple enough?

For the concrete Java code, you should use your own brain, otherwise it will never change that you don’t understand …


If this “100 entries” limit is relevant, you create a list of arrays (List<int[]> arrays) and the sequence of code looks a bit different:

  1. Get the amount of numbers in the file.
  2. Setup a while loop: while( count > 100 ).
  3. In that loop, you create an array for 100 values and store it to the list:
    int [] array = new int [100];
    arrays.add( array );
    
    Further you read the next 100 lines, convert the values to numbers and store them to array [i]; for that, you use a for loop as above.
  4. The last operation in the while loop is this: count -= 100;.
  5. After the while loop, you add the code from above the separator line, with one addition: after creating the array, you need to add it to the list of arrays before you start the for loop.
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement