danielG
danielG

Reputation: 41

How to print 3 different numbers on each line

public static void main(String [] args) {
    for (int i = 0; i < 50; i++) {
        if (i % 3 == 0) {
            System.out.println();
        }
        System.out.print(i+",");
    }
}

This code prints:

0,1,2,
3,4,5,
6,7,8,
...

I want it to print:

0,1,2
1,2,3
2,3,4
3,4,5
...

Any idea? Thanks a lot! I can't use an array.

Upvotes: 0

Views: 334

Answers (6)

alienchow
alienchow

Reputation: 383

From the way you phrase your question, it sounds like you're asking for a solution to your homework. Honestly, I don't see a problem if you actually learn something from this, so please do.

There are a few ways to do it.

If you like println (prints your string and appends a new line character for you):

for(int i=0; i<50; i++) {
    System.out.println(i + "," + (i+1) + "," + (i+2));
}

If you prefer putting in the newline character yourself:

for(int i=0; i<50; i++) {
    System.out.print(i + "," + (i+1) + "," + (i+2) + "\n");
}

Personally, I like string formats when there are only a few arguments:

for(int i=0; i<50; i++) {
    System.out.printf("%d,%d,%d\n", i, i+1, i+2);
}

In fact, if you want to increase the number of numbers per line to say, 10, you could nest a for loop:

int NUMBERS_PER_LINE = 10;

for(int i=0; i<50; i++) {
    for (int j=0; j<NUMBERS_PER_LINE; j++) {
        System.out.print(i+j);

        if (j != NUMBERS_PER_LINE-1) {
            System.out.print(",");
        } else {
            System.out.print("\n");
        }
    }
}

Upvotes: 2

Francesco Bovoli
Francesco Bovoli

Reputation: 326

System.out.println(i + "," + (i+1) + "," + (i+2));

Upvotes: 0

Bhargav Kumar R
Bhargav Kumar R

Reputation: 2200

Try this...

public static void main(String[] args) {

    for (int i=0, j=0, k=0 ; i< 50 ; i++) {
        j = i+1;
        k = j+1;
        System.out.println(i+", "+j+", "+k+" ");
    }
}

Upvotes: 1

Eran
Eran

Reputation: 393771

How about :

for(int i=0;i<50;i++)
{
    System.out.println(i + "," + (i+1) + "," + (i+2));    
}

Upvotes: 5

Ankur Singhal
Ankur Singhal

Reputation: 26067

public static void main(String args[]) throws Exception {
        for (int i = 0 ; i < 50 ; i++) {
            System.out.println(i + "," + (i + 1) + "," + (i + 2));
        }
    }

output

0,1,2
1,2,3
2,3,4
3,4,5
4,5,6

............... so on

Upvotes: 3

herrlock
herrlock

Reputation: 1454

Just calculate the numbers in the for-loop:

for(int i = 0; i < 50; i++)
{
    int n1 = i;
    int n2 = i + 1;
    int n3 = i + 2;
    System.out.println(n1 + ", " + n2 + ", " + n3);
}

Of course you do not have to declare the variables.

Upvotes: 1

Related Questions