• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to seperate an array

 
Georges Vanie
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I'm stuck on how to archive this....any help would be highly appericated! Thanks in advance!


Let's say I have a string array:
String[] tmpPattern = {"p1","p2","p3","p4","p5","p6","p7","p8","p9", "p10", "p11"};

and a header:
String tmpHeader = "Header 1";

Need to print out ---->

Header 1 p1 p2 p3
Header 1 p4 p5 p6
Header 1 p7 p8 p9
Header 1 p10 p11





public class Main {

public static void main(String[] args) {
String tmpHeader = "Header 1";
String[] tmpPattern = {"p1","p2","p3","p4","p5","p6","p7","p8","p9"};
myTest(tmpHeader,tmpPattern);

}

public static void myTest(String header, String[] pattern){


for (int j =0; j <pattern.length; j++){
/*
help needed

*/

}
}

}


Georges
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

There are a couple of different ways to do this, but one simple one is just to have an extra variable that counts the number of items used in a line so far. At the top of the loop, check the value; when it gets to three, print a newline and the heading, and set the counter back to zero. At the bottom of the loop, add one to the counter.

You need to be careful at the very beginning and the very end: you want to print the header even though there is no previous line, and you don't want to print an extra header if the last line has three items in it. Do this with some extra "if" conditions.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49472
64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Posted by Erenst Friedman-Hill or the very similar

[edit]But as Ernest Friedman-Hill says, there is still a risk of problems with the last line of printing.[/edit 13th August]
[edit2]I have lost the bit I quoted from Ernest Friedman-Hill. Sorry. It should have read, "have an extra variable that counts the number of items"[/edit2 14th August]
[ August 14, 2006: Message edited by: Campbell Ritchie ]
 
Georges Vanie
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Erenst!

You point me to the right direction. Now I could print out

Header 1 p1p2p3
Header 1 p4p5p6
Header 1 p7p8p9


The rest 2 elements will be easy to handle...


Thanks again and all the best to you!


Georges
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic