0

How do i read a file and determine the # of array elements without having to look at the text file itself?

String temp = fileScan.toString();
String[] tokens = temp.split("[\n]+");
// numArrayElements = ?
randomname
  • 265
  • 1
  • 9
  • 20

2 Answers2

5

Use the length property of the array:

int numArrayElements = tokens.length;
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
2

The proper expression is tokens.length. So, you can assign numArrayElements like this:

int numArrayElements = tokens.length;

This counts the number of elements in the tokens array. You can count the number of elements in any array in the same way.

tbodt
  • 16,609
  • 6
  • 58
  • 83
  • 3
    Minor detail: `length` does not "count" the number of elements in the array. Rather, it returns the array size which was stored in the array header when the array object was created (and which cannot have changed since). – Hot Licks Sep 23 '13 at 01:05