user3455588
user3455588

Reputation: 17

Java if/for loop assistance

Below is my code...I am trying to make a countdown timer. Right now it works correctly in terms of counting down in the correct sequential order. I am trying to figure out how to place an if statement within the code so that is prints 1 minute and ''seconds, instead of 1 minutes and '' seconds

import java.util.Scanner;

public class countdown {

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    int minutes;
    System.out.println("Please enter the timer countdown in minutes:");
    minutes = scan.nextInt();

    while (minutes < 1) {
        System.out.print("Invalid entry: Enter 1 or more minutes: ");
        minutes = scan.nextInt();
    }
    for (int i = minutes - 1; i >= 0; i--)

    {
        for (int s = 59; s >= 1; s--)

            System.out.println(i + " minutes, " + s + " seconds");
        System.out.println("The timer is done!");

    }

}

}

Upvotes: 1

Views: 291

Answers (3)

leigero
leigero

Reputation: 3283

just add an if/else statement in there:

for (int i = minutes - 1; i >= 0; i--){
    String minute;
    if(minutes == 1)
        minute = " minute ";
    else
        minute = " minutes ";

    for (int s = 59; s >= 1; s--){
        String seconds;
        if(s == 1)
            seconds = " second";
        else
            seconds = " second";
        System.out.println(i + minute + s + seconds);
    }
}

The other answer is probably better, but it uses a different syntax that makes all this code into a short line. They do basically the same thing.

Upvotes: 0

Andy Niles
Andy Niles

Reputation: 36

These two if/else statements should work.

for (int s = 59; s >= 1; s--)
    {
        if (i == 1)
            System.out.print(i + " minute, ");
        else
            System.out.print(i + " minutes, ");
        if (s == 1)
            System.out.println(s + " second");
        else 
            System.out.println(s + " seconds");
    }

Upvotes: 0

Adil Shaikh
Adil Shaikh

Reputation: 44740

Like this,

String minutes = i + (i > 1 ? " minutes" : " minute"); // put this line in outer loop
String seconds = s + (s > 1 ? " seconds" : " second"); // and this line in inner loop

System.out.println(minutes +", "+ seconds);

Upvotes: 1

Related Questions