【问题标题】:Use while loop to print as many times as requested by user使用 while 循环按用户要求打印多次
【发布时间】:2017-11-08 04:44:14
【问题描述】:

你好,我被困在课堂上的编程作业上。任务是制作一个可以计算不同循环的程序。我有正确的提示用户输入代码我想我只是不知道如何让它打印我的消息,我输入的次数。

我希望第二个 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 的值
  • 这是我编译和运行程序时当前打印的内容。输入您要打印的消息?您好 输入您希望您的信息被打印多少次。输入 1-20:5 Row 1.0 - Hello I want it to print Row 1.0 - Hello Row 2.0 - Hello Row 3.0 - Hello etc. 直到输入 numRows 的金额。

标签: java loops while-loop


【解决方案1】:

“可以计算不同循环的程序”是什么意思。目前底部的 while 循环是一个无限循环,因为 numRows 没有被更新。以下是我认为可以解决您的问题的方法:

while (numRows > 0)
{
    System.out.println("Row " + rowNumber++ + " - " +  message);
    rowNumber++;
    numRows--;
}

【讨论】:

    【解决方案2】:

    由于是作业,我不会提供代码。但是您的代码的所有问题都在最后一个 while 循环中。

    首先,您甚至不更改变量 numRows 的值,当然,您也不能退出 while 循环。

    其次,你不需要在这个 while 循环中读取另一个输入,因为所有输入都是在开始时完成的。

    第三,您在代码中添加了两次 rowNumber,显然它不正确,应该更改为其他内容。

    【讨论】:

    • 我知道这是我最后一个 while 循环搞砸了我只是完全不知道如何让它打印出我输入的次数。
    【解决方案3】:

    您的答案将涉及比较 rowNumber 和 numRows 以确定您何时完成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      • 2014-11-28
      • 2021-02-26
      • 1970-01-01
      相关资源
      最近更新 更多