I have the required code for the stopwatch here. All i want is get rid of the Swing part here and display the same output in console. Can anybody help?
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.text.*;
public class ElapsedTime extends JFrame
{
JLabel time;
long startTime = System.currentTimeMillis();
ElapsedTime()
{
setSize(380,200);
setTitle("http://simpleandeasycodes.blogspot.com/");
setLocation(100,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
time = new JLabel("");
time.setFont(new Font("SansSerif",Font.BOLD, 36));
time.setForeground(Color.MAGENTA);
add(time);
//starting new Thread which will update time
new Thread(new Runnable()
{
public void run()
{ try
{
updateTime();
}
catch (Exception ie)
{ }
}
}).start();
}
public void updateTime()
{
try
{
while(true)
{
//geting Time in desire format
time.setText(getTimeElapsed());
//Thread sleeping for 1 sec
Thread.currentThread().sleep(1000);
}
}
catch (Exception e)
{
System.out.println("Exception in Thread Sleep : "+e);
}
}
public String getTimeElapsed()
{
long elapsedTime = System.currentTimeMillis() - startTime;
elapsedTime = elapsedTime / 1000;
String seconds = Integer.toString((int)(elapsedTime % 60));
String minutes = Integer.toString((int)((elapsedTime % 3600) / 60));
String hours = Integer.toString((int)(elapsedTime / 3600));
if (seconds.length() < 2)
seconds = "0" + seconds;
if (minutes.length() < 2)
minutes = "0" + minutes;
if (hours.length() < 2)
hours = "0" + hours;
return minutes+":"+seconds;
}
public static void main(String[] args)
{
JFrame obj = new ElapsedTime();
obj.setVisible(true);
}
}
The keys are:
a.) Finding which character to write to the console in order to remove the most recently-written character (\b, or \010 in ASCII)
b.) Realising that you need to remember how many characters you've written to the console the last time you updated it
c.) Remembering to use print instead of println
public class Test {
public static void main(String[] args) throws InterruptedException {
int charsWritten = 0;
long start = System.currentTimeMillis();
while (1 > 0) {
Thread.sleep(1000);
long elapsedTime = System.currentTimeMillis() - start;
elapsedTime = elapsedTime / 1000;
String seconds = Integer.toString((int) (elapsedTime % 60));
String minutes = Integer.toString((int) ((elapsedTime % 3600) / 60));
String hours = Integer.toString((int) (elapsedTime / 3600));
if (seconds.length() < 2) {
seconds = "0" + seconds;
}
if (minutes.length() < 2) {
minutes = "0" + minutes;
}
if (hours.length() < 2) {
hours = "0" + hours;
}
String writeThis = hours + ":" + minutes + ":" + seconds;
for (int i = 0; i < charsWritten; i++) {
System.out.print("\b");
}
System.out.print(writeThis);
charsWritten = writeThis.length();
}
}
}
Note: you could be more efficient by only clearing the console up to only the characters you are changing but I figure you're not going to get that much of a speed improvement.
Have a look at StopWatch from Apache Commons. It should fulfill your needs.
Here's something that i have figured out myself a little while ago:
public class DelayExample{
static int i,j;
public static void main(String[] args){
for (j= 0; j>=0; j++)
{
for (i = 0; i < 60; i++)
{
System.out.println(j+":" + i);
try
{
Thread.sleep(1000);
}catch (InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
}
}
}
Now i want the clear screen code in Java now. Also i think i have to use System.out.print() instead.
So there a Swing-free solution:
public class ElapsedTime{
long startTime = System.currentTimeMillis();
public ElapsedTime() {
try {
while (true) {
//Clear Console
for (int i = 0; i < 25; i++)
System.out.println();
// geting Time in desire format
System.out.println(getTimeElapsed());
// Thread sleeping for 1 sec
Thread.currentThread().sleep(1000);
}
} catch (Exception e) {
System.out.println("Exception in Thread Sleep : " + e);
}
}
public String getTimeElapsed() {
long elapsedTime = System.currentTimeMillis() - startTime;
elapsedTime = elapsedTime / 1000;
String seconds = Integer.toString((int) (elapsedTime % 60));
String minutes = Integer.toString((int) ((elapsedTime % 3600) / 60));
String hours = Integer.toString((int) (elapsedTime / 3600));
if (seconds.length() < 2)
seconds = "0" + seconds;
if (minutes.length() < 2)
minutes = "0" + minutes;
if (hours.length() < 2)
hours = "0" + hours;
return minutes + ":" + seconds;
}
public static void main(String[] args) {
new ElapsedTime();
}
}
I'm afraid there is no method to clear the console because Java is platform independant. I just insert 25 empty Lines so the last time disappears.
Related
I have a Runner class which extends Thread. In main class, I have bunch of objects of Runner class which start race at the same time. I want to print the rank of each runner based on the time taken to finish their thread.
private void raceStart() throws InterruptedException
{
long start = System.currentTimeMillis();
Thread.sleep((long) (reaction * 1000));
int track = 100;
int playerLocation = 0;
Random randomDelay = new Random();
double delay = 90 + randomDelay.nextInt(16);
for(int i = 0; i <= track; i++)
{
if(playerLocation == track)
{
long finish = System.currentTimeMillis();
double totalTime = (double)(finish - start) / 1000;
System.out.format("%d %d %d %-12s %-12s %-25s %.3f %.3f%n" , rank, lane, bib, country, lastName, firstName, reaction, totalTime);
}
playerLocation++;
Thread.sleep((long) delay);
}
}
In my main class,
private void run()
{
Runner usainBolt = new Runner(1, 6, 2612, "JAM", "Bolt", "Usain", 0.155);
Runner justinGatlin = new Runner(2, 4, 3069, "USA", "GATLIN", "Justin", 0.152);
Runner andreDeGrasse = new Runner(3, 7, 2196, "CAN", "DE GRASSE", "Andre", 0.141);
Runner yohanBlake = new Runner(4, 9, 2611, "JAM", "BLAKE", "Yohan", 0.145);
Runner akaniSimbine = new Runner(5, 3, 2909, "RSA", "SIMBINE", "Akani", 0.128);
Runner benYoussefMeite = new Runner(6, 8, 2245, "CIV", "MEITE", "Ben Youssef", 0.156);
Runner jimmyVicaut = new Runner(7, 5, 2434, "FRA", "VICAUT", "Jimmy", 0.140);
Runner trayvonBromell = new Runner(8, 2, 3054, "USA", "BROMWELL", "Trayvon", 0.135);
List<Runner> runners = Arrays.asList(usainBolt, justinGatlin, andreDeGrasse,
yohanBlake, akaniSimbine, benYoussefMeite, jimmyVicaut, trayvonBromell);
for (Runner r : runners)
{
r.start();
}
I also want to print the total time taken by the whole program in the end.
I tried
long start = System.currentTimeMillis();
run(0);
long finish = System.currentTimeMillis();
double totalTime = (double)(finish - start) / 1000;
System.out.println("totalTime");
But it always prints 0 or 1 before displaying the results.
Since a lot of this is time recording based, I'd recommend creating a simple StopWatch class that each runner can hold on to and record their individual times.
public class StopWatch {
private long startTime = -1;
private long stopTime = -1;
private long currentTime = 0;
private boolean isRunning = false;
public void start(){
isRunning = true;
startTime = System.nanoTime();
}
public void stop(){
stopTime = System.nanoTime();
}
public long getCurrentTime(){
if (startTime != -1 && stopTime == -1){
currentTime = System.nanoTime() - startTime;
}else if (startTime != -1 && stopTime != -1){
currentTime = stopTime - startTime;
}
return currentTime;
}
public boolean isRunning(){
if(startTime != -1 && stopTime == -1){
isRunning = true;
}
return isRunning;
}
public void reset(){
startTime = -1;
stopTime = -1;
currentTime = 0;
isRunning = false;
}
}
I'm not sure what your Runner class looks like but I've made just a simple one that determines speed randomly and adds a random amount every second to each runner(you can create your own method in Runner to determine how quick each runner is). I would also implement comparable to runner so that you can sort them based on distance traveled and finally overide toString() method in Runner to print the relevant information that will be used for the leaderboard later.
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class Runner extends Thread implements Comparable {
boolean hasFinished = false;
int distanceTraveled = 0;
StopWatch timer = new StopWatch();
Random speed = new Random();
int raceDistanceMeters = 100;
private String nameF;
private String nameL;
public Runner(String nameL, String nameF) {
this.nameF = nameF;
this.nameL = nameL;
}
public void run() {
timer.start();
while(hasFinished == false){
try {
Thread.sleep(1000);
distanceTraveled = distanceTraveled + speed.nextInt(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (distanceTraveled >= raceDistanceMeters){
hasFinished = true;
distanceTraveled = raceDistanceMeters;
timer.stop();
}
}
}
#Override
public int compareTo(Object compareRunner) {
int compareDistanceTraveled = ((Runner)compareRunner).distanceTraveled;
return compareDistanceTraveled-this.distanceTraveled;
}
#Override
public String toString() {
return this.nameF + " " + this.nameL + " " + "Distance: " + distanceTraveled + " Time: " + (Double.valueOf(TimeUnit.NANOSECONDS.toMillis(timer.getCurrentTime())))/1000;
}
}
You can now use ArrayLists of type Runner with Collections.sort and also print each of the runners after sorting.
A Race class makes sense as it will allow some house keeping items related to that specific race such as the runners competing along with printing a leaderboard.
public class Race {
ArrayList<Runner> runners = new ArrayList<>();
public void addRunner(Runner runner){
runners.add(runner);
}
public void start(){
runners.forEach(runner -> runner.start());
}
public void printLeaderboard(){
Collections.sort(runners);
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println("-------------------------------------------------------------");
runners.forEach(runner -> System.out.println(runner.toString()));
}
public boolean isRaceOver() {
int count = 0;
for (Runner runner : runners) {
if (runner.hasFinished == true){
count++;
}
}
if (count == runners.size()){
return true;
}
return false;
}
}
So an example of what Main() would look like.
public class Main {
public static void main(String[] args) throws InterruptedException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ArrayList<Runner> runners = new ArrayList<>();
runners.add(new Runner("Bolt", "Usain"));
runners.add(new Runner("GATLIN", "Justin"));
runners.add(new Runner("DE GRASSE", "Andre"));
runners.add(new Runner("BLAKE", "Yohan"));
runners.add(new Runner("SIMBINE", "Akani"));
runners.add(new Runner("MEITE", "Ben Youssef"));
runners.add(new Runner("VICAUT", "Jimmy"));
runners.add(new Runner("BROMWELL", "Trayvon"));
Race race1 = new Race();
runners.forEach(runner -> race1.addRunner(runner));
race1.start();
while (!race1.isRaceOver()){
Thread.sleep(500);
race1.printLeaderboard();
}
System.out.println("Total Run time: " + (Double.valueOf(TimeUnit.NANOSECONDS.toMillis(stopWatch.getCurrentTime())))/1000);
}
}
I need to write a simple program that prints prime numbers up to the given number but no longer than 5 seconds.
Is there some kind of timer to use to interrupt a method after a period of time? (but no interruption if printing is shorter than 5 sec).
Thanks in advance.
My code:
public class Primes {
private static boolean checkIfPrime(int x) {
if (x == 2) return true;
if (x % 2 == 0) return false;
int sqrt = (int) Math.sqrt(x) + 1;
for (int i = 3; i < sqrt; i = i + 2) if (x % i == 0) return false;
return true;
}
private static void printPrimesAndOperationTime(int n) {
long start = System.nanoTime();
for (int i = 2; i <= n; i++) if (checkIfPrime(i)) System.out.println(i);
long end = System.nanoTime();
long timeResult = end - start;
System.out.println("Printing time = " + timeResult + " [ns] => "
+ Math.round(timeResult * 100.0 / 1000000) / 100.0 + " [ms]");
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
printPrimesAndOperationTime(n);
}
}
Used Java Concurrency APIs to solve the above problem. please find inline comments for code walk through.
import java.util.Scanner;
import java.util.concurrent.*;
public class TimeoutInterval {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor(); // Start Single thread executor
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
Future future = executor.submit(new Primes(n)); // Find prime no.
try {
future.get(5, TimeUnit.SECONDS); // Set the time out of the prime no. search task
executor.shutdown();
} catch (TimeoutException e) {
executor.shutdown();
System.out.println("Terminated!");
}
executor.shutdownNow();
}
}
class Primes implements Runnable {
private final int number;
Primes(int number) {
this.number = number;
}
#Override
public void run() {
System.out.println("Started..");
printPrimesAndOperationTime(number);
System.out.println("Finished!");
}
private static boolean checkIfPrime(int x) {
if (x == 2) return true;
if (x % 2 == 0) return false;
int sqrt = (int) Math.sqrt(x) + 1;
for (int i = 3; i < sqrt; i = i + 2) if (x % i == 0) return false;
return true;
}
private static void printPrimesAndOperationTime(int n) {
long start = System.nanoTime();
for (int i = 2; i <= n && !Thread.interrupted(); i++) if (checkIfPrime(i)) {
System.out.println(i);
}
long end = System.nanoTime();
long timeResult = end - start;
System.out.println("Printing time = " + timeResult + " [ns] => "
+ Math.round(timeResult * 100.0 / 1000000) / 100.0 + " [ms]");
}
}
Using ExecutorService, you can submit a task with a timeout. On Receiving the TimeoutException, you should call cancel(true) method on the task to interrupt the thread.
From the documentation
... If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.
I'm making a program that extends the clock to feature the names of the time zones. The derived class needs to have a static String array data member with values: EST, CST, MST, PST, EDT, CDT, MDT, PDT, a zone data member, a default constructor, a constructor with parameters, the setZone() method, the getZone() method, the printTime() method, the toString(), the equals() method, a makeCopy() method, and a getCopy() method.
public class Clock {
private int hr;
private int min;
private int sec;
public Clock() {
hr = 0;
min = 0;
sec = 0;
}
public Clock(int hours, int minutes, int seconds) {
if (0 <= hours && hours < 24) {
hr = hours;
}
else {
hr = 0;
}
if (0 <= minutes && minutes < 60) {
min = minutes;
}
else {
min = 0;
}
if (0 <= seconds && seconds < 60) {
sec = seconds;
}
else {
sec = 0;
}
}
public Clock(Clock otherClock) {
hr = otherClock.hr;
min = otherClock.min;
sec = otherClock.sec;
}
public void setTime(int hours, int minutes, int seconds) {
if (0 <= hours && hours < 24) {
hr = hours;
}
else {
hr = 0;
}
if (0 <= minutes && minutes < 60) {
min = minutes;
}
else {
min = 0;
}
if (0 <= seconds && seconds < 60) {
sec = seconds;
}
else {
sec = 0;
}
}
public int getHours() {
return hr;
}
public int getMinutes() {
return min;
}
public int getSeconds() {
return sec;
}
public void printTime() {
if (hr < 10) {
System.out.print("0");
}
System.out.print(hr + ":");
if (min < 10) {
System.out.print("0");
}
System.out.print(min + ":");
if (sec < 10) {
System.out.print("0");
}
System.out.print(sec);
}
public void incrementHours() {
hr++;
if (hr > 23) {
hr = 0;
}
}
public void incrementMinutes() {
min++;
if (min > 59) {
min = 0;
incrementHours();
}
}
public void incrementSeconds() {
sec++;
if (sec > 59) {
sec = 0;
incrementMinutes();
}
}
public boolean equals(Clock otherClock) {
return (hr == otherClock.hr && min == otherClock.min && sec == otherClock.sec);
}
public void makeCopy(Clock otherClock) {
hr = otherClock.hr;
min = otherClock.min;
sec = otherClock.sec;
}
public Clock getCopy() {
Clock temp = new Clock();
temp.hr = hr;
temp.min = min;
temp.sec = sec;
return temp;
}
public String toString() {
String str = "";
if (hr < 10) {
str = "0";
}
str += hr + ":";
if (min < 10) {
str += "0";
}
str += min + ":";
if (sec < 10) {
str += "0";
}
str += sec;
return str;
}
}
class ExtClock extends Clock {
static String[] timeZone = {"EST", "CST", "MST", "PST", "EDT", "CDT", "MDT", "PDT"};
private String zone;
public ExtClock() {
super();
zone = "";
}
public ExtClock(int hours, int minutes, int seconds, String tz) {
super(hours, minutes, seconds);
zone = tz;
}
public void setZone(int hours, int minutes, int seconds, String tz) {
setTime(hours, minutes, seconds);
zone = tz;
}
public String getZone() {
return zone;
}
public void printTime() {
super.printTime();
System.out.println(" " + zone);
}
public String toString() {
return super.toString() + " " + zone;
}
public boolean equals(ExtClock otherClock) {
return super.equals(otherClock) && zone.equalsIgnoreCase(otherClock.zone);
}
}
public class ExtClockTest {
public static void main(String[] args) {
ExtClock myExtClock = new ExtClock(5,4,30,"EST");
ExtClock yourExtClock = new ExtClock(0,0,0,"");
setZone.yourExtClock(5,45,16,"CDT");
}
}
The derived class compiles fine, but the ExtClockTest program wouldn't compile because it says that it cannot find the symbol. Am I doing something wrong?
You have put the method before the object.
setZone.yourExtClock(5,45,16,"CDT");
It should be:
Obj.method()
yourExtClock.setZone(5,45,16,"CDT");
Under the comment version 4, i am trying to create a method named equals that will test the hours, minutes, and seconds. The formal parameter is used again in the return statement. I know i should have it in the ______.hours format, hours being the instance variable used to test and produce the true or false, but i don't know what should go before the period as the formal parameter. Any suggestions/explanations would be appreciated greatly.
public class Clock
{
private static final byte DEFAULT_HOUR = 0,
DEFAULT_MIN = 0,
DEFAULT_SEC = 0,
MAX_HOURS = 24,
MAX_MINUTES = 60,
MAX_SECONDS = 60;
// ------------------
// Instance variables
// ------------------
private byte seconds,
minutes,
hours;
public Clock (byte hours , byte minutes , byte seconds )
{
setTime(hours, minutes, seconds);
}
public Clock ( )
{
setTime(DEFAULT_HOUR, DEFAULT_MIN, DEFAULT_SEC);
}
public void setTime ( byte hours, byte minutes, byte seconds )
{
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
// hours
if (DEFAULT_HOUR >= 0 && DEFAULT_HOUR <= 29)
{
}
else
{
hours = DEFAULT_HOUR;
}
// minutes
if (DEFAULT_MIN >= 0 && DEFAULT_MIN <= 59)
{
}
else
{
minutes = DEFAULT_MIN;
}
// seconds
if (DEFAULT_SEC >= 0 && DEFAULT_SEC <= 59)
{
}
else
{
seconds = DEFAULT_SEC;
}
}
//--------------------------
// Version 3 mutator methods
//--------------------------
public void incrementSeconds()
{
seconds += 1;
if (seconds >= 59)
{
seconds = DEFAULT_SEC;
incrementMinutes();
}
}
public void incrementMinutes()
{
minutes += 1;
if (minutes >= 59)
{
minutes = DEFAULT_MIN;
incrementHours();
}
}
public void incrementHours()
{
hours += 1;
if (hours >= 23)
{
hours = DEFAULT_HOUR;
}
}
//----------
// Version 4
//----------
public boolean equals(Clock your_clock)
{
return boolean your_clock.hours;
}
//----------
// Version 2
//----------
public String toString()
{
final byte MIN_2DIGITS = 10;
String str = "";
// my input
if (hours < MIN_2DIGITS)
{
str += "0" + hours + ":" ;
}
else
str += hours + ":";
if (minutes < MIN_2DIGITS)
{
str += "0" + minutes + ":" ;
}
else
str += minutes + ":";
if (seconds < MIN_2DIGITS)
{
str += "0" + seconds;
}
else
str += seconds;
//end of my input
return str;
}
} // End of class definition
If you're trying to find equality between the parameter Clock and the caller Clock, I would do the following
public boolean equals(Clock another_clock) {
// Check if 'this' is equal to 'another_clock'
// 1. If you're checking if the pointer is the same
return another_clock.equals(this);
// 2. If you're checking if time is the same (You probably need to create getter/setter methods or change privacy for these fields)
return another_clock.hours == this.hours &&
another_clock.minutes == this.minutes &&
another_clock.seconds == this.seconds;
}
Or something along those lines.
I have a milliseconds and i convert it hh:mm:ss now i want to make it to automatically decrease value overtime.. something like countdown timer
for example, when user sees it, 2:11 0 -> 2:10 59 -> 2:10 58 ...
Below is my code..
Timer t = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
int s = ((TIMER/1000) % 60);
int m = (((TIMER/1000) / 60) % 60);
int h = ((((TIMER/1000) / 60) /60) % 60);
timing.setText(hour + " hours, " + min + " minutes" + sec + " seconds");
timing.repaint();
}
}
t.start();
is it possible?
final Timer t = new Timer(1000, new ActionListener() {
private long time = 10 * 1000; //10 seconds, for example
public void actionPerformed(ActionEvent e) {
if (time >= 0) {
long s = ((time / 1000) % 60);
long m = (((time / 1000) / 60) % 60);
long h = ((((time / 1000) / 60) / 60) % 60);
timing.setText(h + " hours, " + m + " minutes " + s + " seconds");
time -= 1000;
}
}
});
t.start();
As Peter mentioned in his answer, you shouldn't relay on decreasing a number, since there are not guarantees that actionPerformed is invoked right in every second. The below is a working example, which stops the timer on finishing (detailed and therefor code):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test extends JFrame {
private JTextField text;
private Timer timer;
private JButton start;
public Test() {
super("Countdown timer");
text = new JTextField("2", 8);
start = new JButton("Start");
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent click) {
final long current = System.currentTimeMillis();
try {
final long limit = Integer.parseInt(text.getText().trim())* 1000; // X seconds
timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent event) {
long time = System.currentTimeMillis();
long passed = time - current;
long remaining = limit - passed;
if(remaining <= 0) {
text.setText("2");
timer.stop();
} else {
long seconds = remaining/1000;
long minutes = seconds/60;
long hours = minutes/60;
text.setText(String.format("%02d:%02d:%02d", hours, minutes, seconds%60));
}
}
});
timer.start();
} catch(NumberFormatException nfe) {
// debug/report here
nfe.printStackTrace();
}
}});
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(text);
panel.add(new JLabel(" seconds"));
panel.add(start);
add(panel);
}
public static void main(String [] args) throws Exception {
Test frame = new Test();
frame.setDefaultCloseOperation(Test.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
The TIMER value is never decremented by the timer event. Therefore the same time will always be displayed every 1000 milliseconds.
Edit: Assuming "timing" is a Swing component the call to repaint should be unnecessary.
A safer option is to take the actual clock time. The reason for this is that your application can stop for pewriods of time. esp if you machine is busy. This means a countdown timer might not be called as often as you expect. If you use the System.currentTimeMillis() the time will always be right no matter what happens.