简体   繁体   English

如何在java中每行打印10个数字

[英]How to print 10 numbers per line in java

I have a simple but hard problem and wanted to get your help on this.我有一个简单但困难的问题,想得到你的帮助。 This is the code:这是代码:

int i = 0; 
while (i < 100) {
      i++; 
     System.out.print(i);
}

This is the real issue that I'm having, how do I control the println to display how many numbers per line that I want so I don't just see 100 numbers in a row straight?这是我遇到的真正问题,我如何控制 println 以显示我想要的每行多少个数字,这样我就不会直接看到连续100数字? Btw please if at all possible, don't give me the answer but help me to answer it myself instead.顺便说一句,如果可能的话,请不要给我答案,而是帮我自己回答。

while loops? while循环? Why not use for loops?为什么不使用for循环? They are much better in this kind of situation ie when you want to repeat something a known number of times.它们在这种情况下要好得多,即当你想重复某件事已知次数时。

You can use a nested for loop to make this happen:您可以使用嵌套的 for 循环来实现这一点:

int counter = 0;
for (int i = 0 ; i < 10 ; i++) {
    for (int j = 0; j < 10 ; j++) {
        System.out.print (counter);
        System.out.print (" "); // I think it is best to have spaces between the numbers
        counter++;
    }
    //after printing 10 numbers, go to a new line
    System.out.println ();
}

You could do something like:你可以这样做:

    for(int number = 0; number <= 100; number++) {
        if(number % 10 == 0 && number > 0)
            System.out.println(number);
        else
            System.out.print(number + " ");
    }

This would create 10 rows of 10 numbers.这将创建 10 行,每行 10 个数字。

Try this one试试这个

if (i%10==1){
     System.out.println("");
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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