Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

printing certain number of characters per line

Status
Not open for further replies.

DerPflug

Programmer
Mar 28, 2002
153
US
I have an array of integers that I want to print a certain number of characters per line. For instance, I have an array of 10 integers and I want to print 3 integers per line:

9 1 8 3 7 3 7 4 6 5

to print like this:

9 1 8
3 7 3
7 4 6
5

Thanks in advance.
 
Code:
String line = "";
int[] intArray = {9,1,8,3,7,3,7,4,6,5};
int numPerLine = 3;
String sep = " ";

for (int i=0; i<intArray.length; i++)
{
  if (line.length > 0)
  {
    line += sep;
  }
  String line += intArray[i];
  if ((i+1) % numPerLine == 0)
  {
    System.out.println(line);
    line = &quot;&quot;;
  }
}

The i+1 ensures that a single element is not printed the first time (0 mod 3 is 0).

-HavaTheJut
 
Oops. You also need another println(line) after the for loop to take care of the remainder.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top