can u help with this stopwatch?I want that after writting "0" program will end. Stopwatch is working but i dont now how to stop.Thank for your answer.

package stopky;import java.util.Scanner;public class Stopky {public static void main(String[] args) {// TODO Auto-generated method stubScanner sc=new Scanner (; System.out.println("Stlačte 0 pre začatie stopiek."); // "Press 0 for start int start=sc.nextInt();if (start==0) {for(int hodiny=0; hodiny < 24; hodiny++) //hours{ for(int minuty=0; minuty < 60; minuty++) //minutes{ for(int sekundy=0; sekundy < 60; sekundy++) //seconds{for(int ms=0; ms < 1000; ms++) //milisecondstry {Thread.sleep(1);} catch (Exception e) {}{System.out.println(hodiny + ":" + minuty + ":" + sekundy );}}}}}sc.close();}


  • 4
    It's not that easy. You can't stop the program by just typing something as you will only be able to scan for another input after the current task is completed. (Stopwatch stopps counting) You could however solve this problem by using multithreading.– DominikFeb 14 at 21:02
  • for(int ms=0; ms < 1000; ms++) //miliseconds try {Thread.sleep(1);} catch (Exception e) {} can be replaced with try {Thread.sleep(1000);} catch (Exception e) {} or even for better readability try{TimeUnit.SECONDS.sleep(1);} catch (Exception e) {}.– PshemoFeb 14 at 21:36

If you have a for-loop want to quit you need only a "break;" ,so best you have a variable is always watched by whether they are "0", and if so then any for loop executes a break; out. To Example:

import java.util.Scanner;public class Stopky {private volatile static int check=1;public static void main(String[] args) {Scanner sc=new Scanner(;System.out.println("Stlačte 0 pre začatie stopiek."); // "Press 0 for startint start=sc.nextInt();if (start==0) {new Thread(new Runnable() {@Overridepublic void run() {while (check !=0 && sc.hasNextInt())check=sc.nextInt();}}).start();for (int hodiny=0; hodiny < 24; hodiny++) //hours{for (int minuty=0; minuty < 60; minuty++) //minutes{for (int sekundy=0; sekundy < 60; sekundy++) //seconds{for (int ms=0; ms < 1000; ms++) //milisecondstry {Thread.sleep(1);} catch (Exception e) {}{if (check==0)break;System.out.println(hodiny + ":" + minuty + ":" + sekundy);}if (check==0)break;}if (check==0)break;}if (check==0)break;}}sc.close();}}
  • check !="0", check=="0" -> How do I compare strings in Java?– PshemoFeb 14 at 21:21
  • I've just changed the code from a string to an int. This should make it easier to handle.– LetsplaybarFeb 14 at 21:27
  • I would also make check volatile, otherwise threads can use its cached version and ignore its change.– PshemoFeb 14 at 21:33
  • Hm Is it true that otherwise a small delay from interruption can occur, but otherwise something really should not happen in the case.– LetsplaybarFeb 14 at 21:43

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.