Mike F
Mike F

Reputation: 31

How do i output 1-d arrays in a set #(10) per line?

i know i can use many if statements together but i think thats annoying, is there any better way?

    for(index=0; index<alpha.length; index++)
    {
        System.out.print(alpha[index]+ "");
        if (index == 9)
            System.out.println();
        if (index == 19)
            System.out.println();
        if (index == 29)
            System.out.println();
        if (index == 39)
            System.out.println();
    }

Upvotes: 2

Views: 319

Answers (4)

Tom Jefferys
Tom Jefferys

Reputation: 13310

for(index=0; index<alpha.length; index++)
{
    System.out.print(alpha[index]+ "");
    if (index % 10 == 9)
        System.out.println();
}

Upvotes: 0

Danilo Tommasina
Danilo Tommasina

Reputation: 1760

Use the % operator like this:

for(index=0; index<alpha.length; index++)
{
    System.out.print(alpha[index]+ "");
    if ( ( ( index + 1 ) % 10 ) == 0 ) {
        System.out.println();
    }
}

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272762

Use an inner loop (that iterates from 0 to 9 inclusive).

Upvotes: 1

Vladimir Ivanov
Vladimir Ivanov

Reputation: 43108

if ((index + 1) % 10 == 0) 

This(%) is a rest of division.

Upvotes: 3

Related Questions