-3

for a lab i am working on, we are supposed to read in words from a file and get the length of each, and then store it in an array. Would reading in each word into a string and then storing the length in the array be the best way of going about this? And if so, could someone give me a pointer on how to do this? I am a bit lost..

Thanks!

Adam7397
  • 57
  • 1
  • 7

1 Answers1

1

For simple data processing I suggest you use the Streams API

int[] wordLengths = 
   // get all the lines of the file as a stream.
   Files.lines(Paths.get("filename"))
        // split the lines into a stream of words
        .flatMap(s -> Stream.of(s.trim().split(" +")))
        // get the length of each word
        .mapToInt(String::length)
        // turn them into an array.
        .toArray();
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130