如何让扫描仪和计时器同时运行

利亚姆·汉威:

我正在尝试制作一个轮换密码程序,遇到的问题是当该程序要求输入密码时,计时器将停止。我想我可以将程序分为两个操作文件和一个主文件,但是我不想走这条路。

有人对我如何解决此问题有任何想法吗?

'''

if(i == 10)
        {
            System.out.println("New Passcode: ");
            i = -1;
            d = 0;
            passCode.clear();
            Attempt.clear();
            for(int j = 1; j <= 9;j++)
      {
         Random rand = new Random();
         int upperbound = 10;
         int keycode = rand.nextInt(upperbound);
         passCode.add(keycode);
         x++;
      }
         System.out.println(passCode);
         
         //This is the password input
         
               for(int f = 1; f <= 9;f++)
      {
         d++;
         System.out.println("Input one digit at a time; You are on digit " + d);
         int passAtt = input.nextInt();
         Attempt.add(passAtt);
      }
      System.out.println(Attempt);
        }
        else{
            i++;
            System.out.println("Timer: " + i + " Seconds");
        }
        while(x >= 1)
        {
            if(passCode.equals(Attempt))
        {
            System.out.println(" ");
            System.out.println("ACCESS GRANTED");
            System.exit(1);
        }
        }
    }
'''
约翰尼·莫普(Johnny Mopp):

看起来您正在使用整数来标记秒。而是创建一个变量来存储开始时间。然后,只要您想获得经过时间,就从当前时间中减去该时间。例如,使用System.currentTimeMillis()

这是一个简单的类,您可以用来跟踪经过的时间:

class StopWatch
{
    protected long startTime;
    protected long endTime;
    protected boolean running = false;
    
    public void start()
    {
        startTime = System.currentTimeMillis();
        running = true;
    }
    public void stop()
    {
        endTime = System.currentTimeMillis();
        running = false;
    }
    public double getElapsedSeconds()
    {
        if (running) {
            return (System.currentTimeMillis() - startTime) / 1000.0;
        }
        else  {
            return (endTime - startTime) / 1000.0;
        }
    }
}

用法示例:

StopWatch st = new StopWatch();
st.start();
Thread.sleep(1000);  // Simulate long-running operation
System.out.println(st.getElapsedSeconds());
Thread.sleep(5500);  // Another long-running operation
st.stop();
System.out.println(st.getElapsedSeconds());;

输出将是这样的:

1.0 
6.514

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章