如何通过用户输入结束For循环

时间:2018-02-14 20:56:42

标签: java stopwatch

你可以帮忙吗? 这个秒表? 我希望在写完“0”程序结束后。 秒表正在工作,但我现在不知道如何停止。 谢谢你的回答。

package stopky;

import java.util.Scanner;

public class Stopky {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner sc=new Scanner (System.in);     
    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++) //miliseconds
                   try {Thread.sleep(1);} catch (Exception e) {}

               {

                   System.out.println(hodiny + ":" + minuty + ":" + sekundy  );

               }
           }
        }
    }
}
    sc.close();


}

}

1 个答案:

答案 0 :(得分:1)

如果你有一个想要退出的for-loop你只需要一个&#34; break;&#34; , 所以最好你有一个变量总是被它们是&#34; 0&#34;,如果是这样,那么任何for循环执行一个中断;出。举例:

import java.util.Scanner;

public class Stopky {

    private volatile static int check = 1;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Stlačte 0 pre začatie stopiek."); // "Press 0 for start
        int start = sc.nextInt();
        if (start == 0) {
            new Thread(new Runnable() {
                @Override
                public 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++) //miliseconds
                            try {
                                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();
    }
}