首页 文章

使用while循环可以根据用户的要求进行多次打印

提问于
浏览
1

你好,我被困在 class 的编程任务上 . 赋值是创建一个可以计算不同循环的程序 . 我有提示用户输入代码正确我认为我只是无法弄清楚如何使我打印我的消息我输入的次数 .

我希望第二个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++;
        }
    }
}

3 回答

  • 4

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

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

    由于这是一项任务,我不会提供代码 . 但是你的代码的所有问题都在最后一个while循环中 .

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

    其次,在此while循环期间不需要读取另一个输入,因为所有输入都是在开头完成的 .

    第三,你在代码中添加了两次rowNumber,显然,它是不正确的,应该改为其他东西 .

  • 0

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

相关问题