Solving a Java Problem: Countdown Rocket

  • Context: Java 
  • Thread starter Thread starter lypena35
  • Start date Start date
  • Tags Tags
    Java Rocket
Click For Summary
SUMMARY

The forum discussion centers on solving a Java programming problem involving a countdown sequence. The user initially provided incorrect code that did not produce the desired output. The correct solution involves using a for loop that counts down from the user-defined number to 1, printing each number followed by "Blastoff!" after the countdown. The final code snippet provided demonstrates the correct implementation, which is essential for achieving the required output format.

PREREQUISITES
  • Java programming fundamentals
  • Understanding of for loops in Java
  • Basic knowledge of the Java Scanner class
  • Familiarity with console output in Java
NEXT STEPS
  • Explore Java control flow statements, specifically loops
  • Learn about the Java Scanner class for user input
  • Investigate best practices for Java console applications
  • Practice writing Java programs that involve conditional statements and loops
USEFUL FOR

Java beginners, programming students, and anyone looking to improve their skills in writing loops and handling console output in Java applications.

lypena35
Messages
18
Reaction score
0
Hello,
I am stuck on a Java problem in my textbook. Can anyone help me? I have tried many variations to no avail thank you.

Question:Write code that prints: userNum ... 2 1 Blastoff! Your code should contain a for loop. Print a newline after each number and after Blastoff!. Ex: userNum = 3 outputs:
3
2
1
Blastoff!

My code:import java.util.Scanner;

public class CountdownRocket {
public static void main (String [] args) {
int userNum = 0;
int i = 0;

userNum = 3;

for(i=0;i<=userNum;--i){
System.out.println(userNum);
if(i==0){
System.out.println("Blastoff!");
}
}

return;
}
}
 
Technology news on Phys.org
The loop should be like this.

Code:
    for (i = userNum; i > 0; --i){
      System.out.println(i);
      if (i == 1) {
        System.out.println("Blastoff!");
      }
    }

Having [m]return;[/m] at the end of [m]main()[/m] is not necessary.
 
That worked thank you very much! I really appreciate the help!
 
Last edited:

Similar threads

  • · Replies 1 ·
Replies
1
Views
6K
  • · Replies 2 ·
Replies
2
Views
8K
  • · Replies 3 ·
Replies
3
Views
10K
Replies
8
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 2 ·
Replies
2
Views
12K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 1 ·
Replies
1
Views
844
  • · Replies 28 ·
Replies
28
Views
30K