0
How can I make my first Java code work? I'm only level 2 but I want to make a countdown from 5 to 1 with an exclamation.
My code is supposed to be a countdown from 5 to 1. When it reaches 1, I want it to output "Liftoff!". https://code.sololearn.com/c5seZyTZgZ6P/?ref=app
5 ответов
+ 3
// Java code to count down to 1 and then show the word "Liftoff!"
public class Liftoff
{
public static void main(String[] args) {
// size = 12
int x = 5;
while(x > 0) {
if (x == 1) {
System.out.println("Liftoff!");
}else{
System.out.println(x);
}
x--;
}
}
}
+ 3
Considerations: you forgot the closing bracket of the if and for loop
+ 2
//optimized
import java.util.Scanner;
public class Liftoff
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int x =sc.nextInt();
while(x > 0) {
System.out.println(x==1?"Liftoff!" :x);
x--;
}
}
}
+ 1
Thank you Jesus!
+ 1
I found that in order to have an output with the number 1 and with the liftoff exclamation, I also needed to change the while statement to while(x >= 0).
Thanks for your feedback!