Reputation: 109
I wanted to run a timer in background in Java, starting from the moment a message is displayed or printed on the terminal to the the moment the user presses enter after inputting a string. Is it possible to do so? If yes, then how?
Upvotes: 1
Views: 555
Reputation: 4754
Sample code to get time elapsed in seconds for the user input.
import java.util.Scanner;
public class StopWatchDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please type a message: ");
long start = System.currentTimeMillis();
String input = scanner.nextLine();
long end = System.currentTimeMillis();
double elapsedSeconds = (end - start) / 1000.0;
System.out.println("User input: " + input);
System.out.println("Time taken (sec): " + elapsedSeconds);
}
}
Run output:
Please type a message:
This is a user message <press Enter key>
User input: This is a user message
Time taken (sec): 10.106
Upvotes: 1