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++;
}
}
}
我已完成PART1。我对第2部分感到困惑。我如何获得数字序列??
为输出中的每一行编号,并在循环结尾处添加一条消息,说明消息的打印次数。因此,如果用户输入3,您的程序应该打印出来:
1 I love Computer Science!!
2 I love Computer Science!!
3 I love Computer Science!!
Printed this message 3 times.
如果消息被打印N次,请计算并打印从1到N的数字之和。 因此,对于上面的示例,最后一行现在将显示为:
Printed this message 3 times. The sum of the numbers from 1 to 3 is 6.
请注意,您需要添加一个变量来保存总和。
答案 0 :(得分:1)
你有几个选择。您可以使用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);