-4

I have a text file that is reading in Names and Ages printed on the same lines in that order

Example from .txt file:

Matt 25

Bob 19

Steve 30

How can I split the names and the ages so that I can sort the array by ages?

I have heard to use line.split("+") but I am new to java and am unsure of how to implement this.

Azar
  • 1,086
  • 12
  • 27
DTRobertson94
  • 201
  • 1
  • 3
  • 13
  • 1
    Do your own homework. – James McDonnell Apr 10 '14 at 20:28
  • Splitting them off is only the first step as you mention needing to *sort* afterward; you still need an association between the age and name. There's number of approaches to that, which I suspect is the point of the homework. – Brian Roach Apr 10 '14 at 20:34

1 Answers1

1

Split the string with the following line (I'm supposing the line you've read is in the variable line);

String[] bits = line.split("\\s+");

then get the integer value with the following:

int newInt = Integer.parseInt(bits[1]);
BenMorel
  • 34,448
  • 50
  • 182
  • 322
AntonH
  • 6,359
  • 2
  • 30
  • 40
  • hey what does ("\\s+") do? why not just (" ") – j.con Apr 10 '14 at 20:28
  • @j.con "one or more whitespace characters". It's the safer way to split a sentence on space as it doesn't care the number of spaces between words. – Brian Roach Apr 10 '14 at 20:29
  • `"\\s"` means one whitespace character (includes space, tab, and others). `+` means "at least one". Putting them together as `"\\s+"` means "at least one whitespace character". – AntonH Apr 10 '14 at 20:29
  • 1
    robust, i like it. thanks – j.con Apr 10 '14 at 20:30