【发布时间】:2018-04-20 07:30:32
【问题描述】:
大家好,我遇到了一个问题,无法提出解决方案。我正在使用一个while循环,做while循环和for。我知道我的前两个 while 循环是正确的,我想要完成的是让我的 do while 循环和 for 语句打印出与我的第二个 while 循环完全相同的东西。
import java.util.Scanner;
public class CountingLoops{
public static void main(String[] args){
String message; // First message prompt
String inputString; // For reading input.
double numRows; // Number to be asked.
double rowNumber = 1;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the message you want to print? ");
message = keyboard.nextLine();
System.out.println ("Enter how many times you want your message to be printed. Enter the value from 1-20:" );
numRows = keyboard.nextDouble();
while (numRows > 20 || numRows < 1){
System.out.println("Number was not between 1-20. Try Again.");
System.out.println("Enter how many times you want your message to be printed. Enter the value from 1-20: ");
numRows = keyboard.nextDouble();
}
System.out.println("Output using while loop...");
while (numRows > 0){
System.out.println("Row " + rowNumber + " - " + message);
rowNumber++;
numRows--;
}
System.out.println("Times in while loop:" + numRows);
System.out.println("Output using do-while loop...");
do {
System.out.println("Row " + rowNumber + " - " + message);
numRows--;
rowNumber++;
} while (numRows > 0);
System.out.println("Times in do-while loop..." + numRows);
System.out.println("Output using for-loop:");
for (numRows = 1; numRows < 20; numRows++){
System.out.println("Row " + rowNumber + " - " + message);
numRows--;
rowNumber = keyboard.nextDouble();
}
}
}
输入您要打印的消息?
你好
输入您希望将消息打印多少次。输入 1-20 的值:
5
使用while循环输出...
第 1.0 行 - 你好
第 2.0 行 - 你好
第 3.0 行 - 你好
第 4.0 行 - 你好
第 5.0 行 - 你好
while 循环中的时间:0.0
使用 do-while 循环输出...
第 6.0 行 - 你好
do-while 循环中的时间...-1.0
使用for循环输出:
第 7.0 行 - 你好
(这是我运行程序时打印的内容,下面是我要打印的内容)
使用while循环输出...
第 1.0 行 - 你好
第 2.0 行 - 你好
第 3.0 行 - 你好
第 4.0 行 - 你好
第 5.0 行 - 你好
while 循环中的时间:5
使用 do-while 循环输出...
第 1.0 行 - 你好
第 2.0 行 - 你好
第 3.0 行 - 你好
第 4.0 行 - 你好
第 5.0 行 - 你好
do while 循环次数:5
使用for循环输出...
第 1.0 行 - 你好
第 2.0 行 - 你好
第 3.0 行 - 你好
第 4.0 行 - 你好
第 5.0 行 - 你好
for 循环次数:5
【问题讨论】:
-
您是否尝试过在循环之间重置变量?
标签: java loops for-loop do-while