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 = ?
3
  • 3
    Do you mean tokens.length ? Commented Sep 22, 2013 at 23:25
  • Almost duplicate of: stackoverflow.com/questions/453018/… . This has been answered and more effectively. Commented Sep 22, 2013 at 23:29
  • Unlike C/C++, in Java you can always determine the size of an array using length. Commented Sep 23, 2013 at 1:03

2 Answers 2

5

Use the length property of the array:

int numArrayElements = tokens.length;
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.