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
- Read the first line and convert the result to a number that you store to
count
. - Then add this line:
int [] array = new int [count];
- 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 toarray [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:
- Get the amount of numbers in the file.
- Setup a
while
loop:while( count > 100 )
. - In that loop, you create an array for 100 values and store it to the list:
Further you read the next 100 lines, convert the values to numbers and store them to
int [] array = new int [100]; arrays.add( array );
array [i]
; for that, you use afor
loop as above. - The last operation in the
while
loop is this:count -= 100;
. - 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 thefor
loop.