Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with String[]

Tags:

java

I have a String[] LinesFromFile which contains about 100 lines loaded from a file e.g.

LinesFromFile[0] is "Line1"

LinesFromFile[1] is "Line2"

LinesFromFile[2] is "Line3"

...

LinesFromFile[99] is "Line100"

I want to now create a new String[] SomeLinesFromFile and assign this variable some of the lines from LinesFromFile.

I would have thought it would have been as simple as:

String[] SomeLinesFromFile = null;
int offset = 45;

for (i = 0; i < 10, i++)
{
    SomeLinesFromFile[i] = LinesFromFile[offset + i];
}

I would have assumed this code would set SomeLinesFromFile[0] to SomeLinesFromFile[9] with the values of LinesFromFile[46] through to LinesFromFile[56].

When I try running this on my android device it crashes. What am I missing here?

like image 464
automationguy Avatar asked Jul 30 '26 17:07

automationguy


1 Answers

String[] SomeLinesFromFile = null;

SomeLinesFromFile is null, so you cannot then do:

SomeLinesFromFile[i] = ...

You need to create an array first, e.g.:

String[] SomeLinesFromFile = new String[10];


Incidentally, it is considered bad practice to name your variables starting with capital letters. So you should always use someLinesFromFile instead of SomeLinesForFile.
like image 114
Oliver Charlesworth Avatar answered Aug 01 '26 08:08

Oliver Charlesworth