简体   繁体   中英

How do I make this table 0-9 with loops in Java?

How do I make this table?
This is what should be the outcome:

        0 1 2 3 4 5 6 7 8 9                         
        1 2 3 4 5 6 7 8 9 0
        2 3 4 5 6 7 8 9 0 1
        3 4 5 6 7 8 9 0 1 2
        4 5 6 7 8 9 0 1 2 3
        5 6 7 8 9 0 1 2 3 4
        6 7 8 9 0 1 2 3 4 5
        7 8 9 0 1 2 3 4 5 6
        8 9 0 1 2 3 4 5 6 7
        9 0 1 2 3 4 5 6 7 8

And this is the best I could come up with:

for (int i = 0; i < 10; i++)

 {
    for (int j = 0; j < 10; j++) {
                if (i + j < 10) {
                    System.out.print(i + j);
                } else
                    System.out.print("x");
            }

            System.out.println();

        }

    }
}

I simply can't find a solution how to get numbers running again past 9 with the beginning of 0,1,2,3 etc. My code would generate next:

        0123456789
        123456789x
        23456789xx
        3456789xxx  
        456789xxxx
        56789xxxxx
        6789xxxxxx 
        789xxxxxxx
        89xxxxxxxx
        9xxxxxxxxx 

You can do:

System.out.print((i + j) % 10);

To turn 10 into 0 , 11 into 1 , etc.

Try this:

for (int i=0; i<10; i++) {
  for (int j=i; j<i+10; j++) {
    System.out.print(j%10);
  }
  System.out.println();
}

The key here is to use % (modulo) operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM