编写一个 while 循环来输出从 0 到 n 互斥的整数值

如何编写一个 while 循环来输出从 0 到 n 独占的整数值。


输出应每行有五个值,值之间用空格分隔。我可以在同一行上完成,但是我对每行的五个值感到困惑。我应该在哪里添加while循环来做到这一点?


import java.util.Scanner;


public class While

{

   public static void main( String[] args)

   {

      Scanner scan = new Scanner( System.in);


      // constants


      // variables

      int n;

      int value;



      // program code

      value = 0;

      System.out.println( "Enter an integer ");

      n = scan.nextInt();

      if( n <=0){

         System.out.println( "Error");

      }else

         while ( value < n){

         System.out.print( value + " ");

         value = value + 1;

      }

   }

}


杨__羊羊
浏览 250回答 3
3回答

人到中年有点甜

您可以使用模数运算符来确定是否value是 的倍数5,如果是,则打印换行符:while (value < n){&nbsp; &nbsp; &nbsp;System.out.print(value + " ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp;if(value %5 == 4) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;value = value + 1;}输出:(输入为 10)0 1 2 3 4&nbsp;5 6 7 8 9&nbsp;

慕的地8271018

您只需要System.out.println();在每 5 个元素之后添加一个:&nbsp; &nbsp; while ( value < n){&nbsp; &nbsp; &nbsp; &nbsp; System.out.print( value + " ");&nbsp; &nbsp; &nbsp; &nbsp; value = value + 1;&nbsp; &nbsp; &nbsp; &nbsp; if (value % 5 == 0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; }

慕容708150

这一行代码将每行打印五个值,值用空格分隔: System.out.print(value % 5 == 0 ? "\n" : " ");\n是换行符。在print方法中\n给出换行符。所以,如果(value % 5 == 0)等于true该行打印一个换行符,否则打印空间。因此你while loop应该是这样的:while (value < n) {&nbsp; &nbsp; System.out.print(value);&nbsp; &nbsp; value = value + 1;&nbsp; &nbsp; System.out.print(value % 5 == 0 ? "\n" : " ");}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java