繁体   English   中英

使用while循环可按用户要求多次打印

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM