Nautical bell: Difference between revisions

(→‎{{header|J}}: improve comments in callWatch)
(→‎{{header|Java}}: added Java)
Line 305:
 
'''Notes''': I tested the <tt>clock2ship</tt>, <tt>callWatch</tt>, and <tt>ringBell</tt> functions, but didn't actually have the patience to test <tt>shipsWatch</tt> over a 24-hour period. Use at your own risk (but don't use it to keep watch on your galleon, please).
 
=={{header|Java}}==
This code uses UTC time.
{{trans|D}}
<lang java>import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
 
public class NauticalBell extends Thread {
 
public static void main(String[] args) {
NauticalBell bells = new NauticalBell();
bells.setDaemon(true);
bells.start();
try {
bells.join();
} catch (InterruptedException e) {
System.out.println(e);
}
}
 
@Override
public void run() {
DateFormat sdf = new SimpleDateFormat("HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
 
int numBells = 0;
long time = System.currentTimeMillis();
long next = time - (time % (24 * 60 * 60 * 1000)); // midnight
 
while (next < time) {
next += 30 * 60 * 1000; // 30 minutes
numBells = 1 + (numBells % 8);
}
 
long wait = 0;
while (true) {
time = System.currentTimeMillis();
if (time - next >= 0) {
String bells = numBells == 1 ? "bell" : "bells";
String timeString = sdf.format(time);
System.out.printf("%s : %d %s\n", timeString, numBells, bells);
next += 30 * 60 * 1000;
wait = next - time;
numBells = 1 + (numBells % 8);
}
try {
Thread.sleep(wait);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}</lang>
 
Sample output:
 
<pre>...
13:00:00 : 2 bells
13:30:00 : 3 bells
14:00:00 : 4 bells
...</pre>
 
=={{header|Perl 6}}==
Anonymous user