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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34561469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:03:02  来源:igfitidea点击:

How to print 10 numbers per line in java

java

提问by Dumbfounded

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 100numbers in a row straight? Btw please if at all possible, don't give me the answer but help me to answer it myself instead.

这是我遇到的真正问题,我如何控制 println 显示我想要的每行多少个数字,这样我就不会直接看到100连续的数字?顺便说一句,如果可能的话,请不要给我答案,而是帮我自己回答。

回答by Sweeper

whileloops? Why not use forloops? They are much better in this kind of situation i.e. when you want to repeat something a known number of times.

while循环?为什么不使用for循环?它们在这种情况下要好得多,即当您想重复某件事已知次数时。

You can use a nested for loop to make this happen:

您可以使用嵌套的 for 循环来实现这一点:

int counter = 0;
for (int i = 0 ; i < 10 ; i++) {
    for (int l = 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 ();
}

回答by Amit

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 个数字。

回答by Java noob

Try this one

试试这个

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