如何使用 for 循环对输出中的每一行进行编号?

How to number each line in the output using a for loop?

import java.util.Scanner;

public class LoveCS
{
    public static void main(String[] args) 
    {
        int noTimesPrinted;

        Scanner scan = new Scanner(System.in);

        System.out.print("How many times should the message be printed: ");
        noTimesPrinted = scan.nextInt();

        int count = 1;
        while (count <= noTimesPrinted) 
        {
            System.out.println(" I love Computer Science!!");
            count++;
        }
    }
}
  1. 不使用常量 LIMIT,而是询问用户消息应该打印多少次。您需要声明一个变量来存储用户的响应并使用该变量来控制循环。 (请记住,所有大写仅用于常量!)

我已经完成了第 1 部分。我卡在 PART2 上了。如何获取编号顺序??

  1. 为输出中的每一行编号,并在循环末尾添加一条消息,说明该消息被打印了多少次。所以如果用户输入 3,你的程序应该打印:

     1 I love Computer Science!!
     2 I love Computer Science!!
     3 I love Computer Science!!
     Printed this message 3 times.
    
  2. 如果消息被打印N次,计算并打印从1到N的数字之和。 所以对于上面的例子,最后一行现在应该是:

    Printed this message 3 times. The sum of the numbers from 1 to 3 is 6.
    

    请注意,您需要添加一个变量来保存总和。

你有几个选择。您可以使用 String 连接,

int count = 1;
while (count <= noTimesPrinted) 
{
    System.out.println(Integer.toString(count) + " I love Computer Science!!");
    count++;
}
System.out.println("Printed this message " + noTimesPrinted + " times");

或者使用 printf 和(因为你说你想要一个 for 循环)像

for (int count = 1; count <= noTimesPrinted; count++) {
    System.out.printf("%d I love Computer Science!!%n", count);
}
System.out.printf("Printed this message %d times%n", noTimesPrinted);