• Post Reply Bookmark Topic Watch Topic
  • New Topic

split numerical data based on column  RSS feed

 
Tai Yo
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to split numerical data based on column.
For example, these data have 4 columns:

And I am using this code to manipulate each column data:

But the problem is I don't know how many columns can be there, maybe 3 or 6 column data.
So I would like to ask, how can I write if there are unknown number of columns?
Any help is greatly appreciated.
 
Tony Docherty
Bartender
Posts: 3264
81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The split method will return an array with an element for each column so the length of the array will be the number of columns you have.

The printf method has a format string parameter and a varargs parameter so you don't need to specify each array element you can just pass the whole array which leaves just the format string to sort out.

The format string needs one "%11s " for every column and given that you know how many columns there are (ie the length of the tokens array) you can have a loop for the length of the tokens array that concatenates the correct number of "%11s " and finally concatenates a "\n" (your code shows %n but I'm guessing this is a typo and should be \n) into a string variable which you pass as the format string to printf().
 
Campbell Ritchie
Sheriff
Posts: 55351
157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why are you using nextLine? If you are reading a file with predictable contents, you can get the individual tokens as their numeric equivalents.You can wrap that in a loop while (scan.hasNext()) ... (or similar), and use that to iterate the whole file. Note that sort of programming depends on the file being a certain format, so you could call it tight coupling to the file
 
Winston Gutkowski
Bartender
Posts: 10573
65
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tai Yo wrote:So I would like to ask, how can I write if there are unknown number of columns?

Loop and split based on lines, and format each column separately.

Eg, something like:There are variations depending on whether you want to include "blank" lines or not.

Winston
 
Tai Yo
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for your response. All the answers deserves the highest respect. It is solved my problem. Thank you again for taking your time.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!