Hey i stayed up all night trying to figure this out, so im asking you to help me solve this problem so I can get back to sleep
The problem: I've created a simple console stopwatch program. When i press ENTER the watch starts running from time 0:0:0, next time i press ENTER the time that has elapsed is printed, for example 0:0:10 (10 seconds).
BUT, when i press ENTER again i want the stopwatch to resume on the previous time! This should be a simple logical problem but im blind for the moment so really nice if you could help me out
import java.io.IOException; import java.util.Date; public class Main { public static Date timeStampFirst = new Date(); public static void main(String[] args) { Timer timer = new Timer(); Thread t1 = new Thread(timer); t1.start(); } }
import java.io.IOException; import java.util.Calendar; import java.util.Date; public class Timer implements Runnable { private boolean isRunning = false; long elapsedTime = 0; long tempTime = 0; @Override public void run() { isRunning = true; long previousTime = 0; while (isRunning) { try { System.out.println("Press any key to start/stop stopwatch"); if (System.in.read() != -1) { Date timeStamp = new Date(); if (tempTime == 0) { tempTime = timeStamp.getTime(); Main.timeStampFirst.setTime(tempTime); } Main.timeStampFirst.setTime(timeStamp.getTime() - elapsedTime); System.out.println("Running..."); } if (System.in.read() != -1) { System.out.println("Stopped!"); Date timeStampStop = new Date(); elapsedTime = timeStampStop.getTime() - Main.timeStampFirst.getTime() - 3600000; previousTime = elapsedTime; Date finishTime = new Date(); finishTime.setTime(elapsedTime); System.out.println("Time elapsed: " + finishTime.getHours() + ":" + finishTime.getMinutes() + ":" + finishTime.getSeconds()); timeStampStop.setTime(0); finishTime.setTime(0); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }