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++;
}
}
}
I HAVE COMPLETED PART1. I AM STUCK ON PART2. How do I get the number sequence??
Number each line in the output, and add a message at the end of the loop that says how many times the message was printed. So if the user enters 3, your program should print this:
1 I love Computer Science!!
2 I love Computer Science!!
3 I love Computer Science!!
Printed this message 3 times.
If the message is printed N times, compute and print the sum of the numbers from 1 to N. So for the example above, the last line would now read:
Printed this message 3 times. The sum of the numbers from 1 to 3 is 6.
Note that you will need to add a variable to hold the sum.
You have a few choices. You could use String
concatenation,
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");
Or with printf
and (since you said you wanted a for
loop) something like
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);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments