Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialYusuf Mohamed
2,631 PointsQuestion about java/android logic.
I'm currently trying to create a countdown timer for a project of mine. It is working but I was just trying to understand one part.
private void startStop() {
if(timerRunning){
stopTimer();
} else {
startTimer();
}
For some context, timerRunning is a boolean that's set to its default (which is false). The startstop method is a method for used in a onclick method for a button.
So the code says "If false stop timer. Else (if true) start timer".
So if the code by default is false how can it start the timer?
4 Answers
Steve Hunter
57,712 PointsHi Yusuf,
The code will work as you describe.
So if the code by default is false how can it start the timer?
If timerRunning
is set to false
by default, the else
clause will run. The else
clause calls the funtion startTimer()
which, presumably, makes the time start!
private void startStop() {
if(timerRunning){
stopTimer(); // this won't run if timerRunning is false
} else {
startTimer(); // but this will run so your timer will start
}
} // I added this
I hope that helps.
Steve.
KRIS NIKOLAISEN
54,972 PointsWouldn't the logic be if timer is running (timerRunning = true) stop timer? How do you stop the timer if it isn't running? It is already stopped.
Yusuf Mohamed
2,631 PointsThat's the problem I'm not understanding, it shouldn't work the way I'm doing it but the timer is working so idk if there's something we're missing.
Yusuf Mohamed
2,631 PointsBumpidity bump.
Lauren Moineau
9,483 PointsHi Yusuf. Actually, your code reads "if true, stop timer, else, start timer", so it works perfectly.
Writing
if (timerRunning){
// (..)
}
is the same as writing
if (timerRunning == true) {
// (...)
}
I know it's confusing at first.
By the way, if you'd like to check if a Boolean has a value of false
, just write
if (! timerRunning) {. // Instead of (timerRunning == false)
// (...)
}
Hope that helps :)
Yusuf Mohamed
2,631 PointsYusuf Mohamed
2,631 PointsOkay so when the value is false, that's when the else clause will run.