Hey guys,
Recently I made the decision to learn Java programming on my own (I only bought a book, no course). So far I've covered the following relevant topics:
-Elementary Programming: Identifiers, Variables, Data types...
-Selections: boolean, if (else if, else) statements, logical operators, switch statements...
-Loops: while, do-while, for, nested loops, keywords break and continue... (=> Currently doing the exercises of this chapter).
In one of the last exercises of the latter chapter I'm asked to make a countdown timer. The only method to capture time the book has covered yet is the currentTimeMillis method in the System class.
I'm aware this problem probably can be solved in an easier and more efficient way using the Timer class, but imagine I follow the book strictly and I have never heard of it.
So far I have tried a number of things, without succes obviously, this is the best I came up with:
import java.util.Scanner; public class Exercise4_43 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the number of seconds: "); int interval = input.nextInt(); long startTime = System.currentTimeMillis(); long endTime = System.currentTimeMillis() + (interval * 1000); while (System.currentTimeMillis() < endTime) { if ((endTime - System.currentTimeMillis()) % 1000 == 0){ System.out.println(((endTime - System.currentTimeMillis()) / 1000) + " seconds remaining."); } } System.out.println("Stopped."); } }
When I run the program and e.g. enter 10 as input I get the following output:
10 seconds remaining
//1 second later
9 seconds remaining
9 seconds remaining
9 seconds remaining
9 seconds remaining
//another second later
8 seconds remaining
8 seconds remaining
8 seconds remaining
8 seconds remaining
//another second later
7 seconds remaining
7 seconds remaining
7 seconds remaining
7 seconds remaining
....
0 seconds remaining
Stopped.
Can someone please give me a hint so I can solve this problem? (Please, don't give a possible solution, if I can't solve the problem myself I miss the opportunity to acquire some extra insight in this kind of problems).
Thanks in advance!
Cheers
Michael