Dullah
Dullah

Reputation: 53

Java append newline every n lines

String[] names = new String[18];
names[0] = "James Raider";
names[1] = "Calm Hain";
names[2] = "Ewds Ashby";
names[3] = "Gedge Taylor";
names[4] = "Hay Fin";
names[5] = "Ian Hilton";
names[6] = "John Coke";
names[7] = "Nathan Dryer";
names[8] = "Jess Maguire";
names[9] = "Jamie Loyal";
names[10] = "Luke Shwinger";
names[11] = "Parrot Tom";
names[12] = "John Clarke";
names[13] = "Steven Mason";
names[14] = "Shing Lao";
names[15] = "Tom Brook";
names[16] = "Arthitus Pint";
names[17] = "Yifan Yao";

StringBuilder sb = new StringBuilder();
ArrayList<Integer> list = new ArrayList();
for (int i = 0; i < names.length; i++) {
    list.add(i);
}
Collections.shuffle(list);
for (int i = 0; i < names.length; i++) {
    field.append(names[list.get(i)] + "\n");
    for (int u = 0; u < (Integer) number.getValue(); u++) {
        field.append("\n");
    }
}

I am trying to add a new line to the output, every number.getValue() amount of times. What I'm doing adds it after every line, but I only want it to create it after a set number of times.


Example: 3 times

Harry
John 
Jake

Amanda
Holly
Sam

Upvotes: 4

Views: 2891

Answers (3)

The Law
The Law

Reputation: 334

Just add if statement in your for loop that prints new line after every n-lines of outputs (I believe that is what you wanted, not after n-iterations). Lets say you want new line every 3 lines Pseudo code:

int newLine = 3;
int multiplicator = 1;
for(int i = 0; i< names.length; i++){
  if( newLine == i){
    // print extra line after every 3rd output        
    field.append("\n");
    newLine = 3; //to reset variable to the correct delimiter on each subsequent n-th iteration
    multiplicator++;
    newLine = newLine * multiplicator;
  }
field.append(names[i] + "\n")
// print regular value on normal line during every iteration
}

Upvotes: 2

budi
budi

Reputation: 6551

This should get you your desired output.

for (int i = 0; i < names.length; ++i) {
    // add name to field
    field.append(names[list.get(i)]);
    field.append('\n');

    // every number.getValue() names, add a new line
    if (i % number.getValue() == (number.getValue() - 1)) {
        field.append('\n');
    }
}

EDIT: Upon editing your original post, I saw some formatting was lost in your example. Updated my answer accordingly.

Upvotes: 1

gonzo
gonzo

Reputation: 2121

You can use mod to help you out with this. Something like this:

for (int i=0; i<names.length; i++) {
    field.append(names[list.get(i)]+"\n");
    if (i%3==0){
        //Do Stuff here every 3rd iteration. 
    }
}

Not sure when you want to print but mod, %, just takes the remainder of the number. Very useful when looping. So in the above example it would only go inside the if when i divided by 3 has no remainder. So for the following i:

0 3 6 9 12 15

Hope this helps!

Upvotes: 0

Related Questions