[英]JAVA: Use While Loop to print out character as many times as the number read in
[英]Use while loop to print as many times as requested by user
您好,我被困在課程的編程上。 任務是制作一個可以計算不同循環的程序。 我有正確的提示用戶輸入代碼,我想我只是想不出如何使它按輸入的次數打印消息。
我希望第二個while循環打印類似
第1行-您好
第2行-您好
第3行-您好
第4行-您好
對於我輸入的數字。
謝謝您的幫助。
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.print("Enter the message you want to print? ");
message = keyboard.nextLine();
System.out.print("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.print("Number was not between 1-20. Try Again.");
System.out.print("Enter how many times you want your message to be printed. Enter the value from 1-20: ");
numRows = keyboard.nextDouble();
}
while (numRows <= 20)
{
System.out.println("Row " + rowNumber++ + " - " + message);
rowNumber = keyboard.nextDouble();
rowNumber++;
}
}
}
您所說的“可以計數不同循環的程序”是什么意思。 目前,由於numRows尚未更新,因此底部while循環是一個無限循環。 我相信這可以解決您的問題:
while (numRows > 0)
{
System.out.println("Row " + rowNumber++ + " - " + message);
rowNumber++;
numRows--;
}
由於這是一項任務,因此我將不提供代碼。 但是代碼的所有問題都在最后的while循環中。
首先,您甚至不更改變量numRows的值,當然,您不能退出while循環。
其次,由於所有輸入都是在開始時完成的,因此您無需在while循環中讀取其他輸入。
第三,您在代碼中兩次添加了rowNumber,顯然,它是不正確的,應將其更改為其他內容。
您的答案將涉及比較rowNumber和numRows以確定何時完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.