猿问

在 Java 中的不同行中,Do-While 循环计数 1 到 30

我目前正在学习所有类型的循环的 Java 课程,并且被困在一个专门关于 do-while 循环的问题上。问题要求我们创建一个从 1 到 30 计数的 do-while 循环,计数在 10 个整数后跳到下一行,例如:


1 2 3 4 5 6 7 8 9 10


11 12 13 14 15 16 17 18 19 20


21 22 23 24 25 26 27 28 29 30

我的循环开始了,我可以让它打印值 1 到 30,但我不确定如何让它每 10 个整数跳过一行。这是我当前的代码:


int q = 0;

do

{       

    q=q+1;

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

}

while (q<30);

System.out.println();


海绵宝宝撒
浏览 214回答 3
3回答

陪伴而非守候

将此行添加到您的代码中,它将起作用。if&nbsp;(q&nbsp;%&nbsp;10&nbsp;==&nbsp;0)&nbsp;System.out.println();如果q能被 10 整除,那么你写一行到系统出来。将其放在该行之后&nbsp;System.out.print(q+" ");

绝地无双

这是一个关于如何让该行跳过每 10 个整数的示例:public class App&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; public static void main( String[] args )throws IOException{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int y = 1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int x = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(y + " ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; y++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(x >= 10) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;x = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}while(y <= 30);&nbsp; &nbsp;}}我们可以做的是创建一个“控制”变量(x)。我们可以在循环期间每次增加它。当 x >= 10 时,我们可以打印一个空行。当我们的 y 变量 <= 30 时,我们将每次打印。 这是程序的输出:1 2 3 4 5 6 7 8 9 10&nbsp;11 12 13 14 15 16 17 18 19 20&nbsp;21 22 23 24 25 26 27 28 29 30&nbsp;

倚天杖

&nbsp; &nbsp;int q = 0;do{&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; q=q+1;&nbsp; &nbsp; System.out.print(q+" ");&nbsp; &nbsp; if(q% 10==0)&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;}while (q<30);
随时随地看视频慕课网APP

相关分类

Java
我要回答