jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes How to seperate an array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to seperate an array" Watch "How to seperate an array" New topic

How to seperate an array

Georges Vanie

Joined: Aug 13, 2006
Posts: 2

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"};


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

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




Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199


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.

[Jess in Action][AskingGoodQuestions]
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46437
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

Joined: Aug 13, 2006
Posts: 2
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!

I agree. Here's the link: http://aspose.com/file-tools
subject: How to seperate an array
It's not a secret anymore!