I am truely sorry if asking the same question twice is considered spamming as I already asked about backward timer a hour ago.
But now new problem with it is though I couldn't get anyone's attention to that question again. I have successfully coded the timer thanks to you guys but then I tried to convert seconds tot he hh:mm:ss format but it didn't work. Instead of continuosely going till it is 00:00:00. It just shows the time that I coded it and that's it.
Here's my code.
import java.util.Timer;
import java.util.TimerTask;
public class countdown extends javax.swing.JFrame {
public countdown() {
initComponents();
Timer timer;
timer = new Timer();
timer.schedule(new DisplayCountdown(), 0, 1000);
}
class DisplayCountdown extends TimerTask {
int seconds = 5;
int hr = (int)(seconds/3600);
int rem = (int)(seconds%3600);
int mn = rem/60;
int sec = rem%60;
String hrStr = (hr<10 ? "0" : "")+hr;
String mnStr = (mn<10 ? "0" : "")+mn;
String secStr = (sec<10 ? "0" : "")+sec;
public void run() {
if (seconds > 0) {
lab.setText(hrStr+ " : "+mnStr+ " : "+secStr+"");
seconds--;
} else {
lab.setText("Countdown finished");
System.exit(0);
}
}
}
public static void main(String args[]) {
new countdown().setVisible(true);
}
Move your calculations
int hr = seconds/3600;
int rem = seconds%3600;
int mn = rem/60;
int sec = rem%60;
String hrStr = (hr<10 ? "0" : "")+hr;
String mnStr = (mn<10 ? "0" : "")+mn;
String secStr = (sec<10 ? "0" : "")+sec;
into the run method.
public String getCountDownStringInMinutes(int timeInSeconds)
{
return getTwoDecimalsValue(timeInSeconds/3600) + ":" + getTwoDecimalsValue(timeInSeconds/60) + ":" + getTwoDecimalsValue(timeInSeconds%60);
}
public static String getTwoDecimalsValue(int value)
{
if(value>=0 && value<=9)
{
return "0"+value;
}
else
{
return value+"";
}
}
Related
I have an object List<...> and I have using it in my xyz java class its stored some data in its memory successfully and I can use it within xyz class but i have one another class as abc and I want to use this List<...> in it , but when I create an object of my xyz class in abc class and set the getter of my List<...> it shows me null.
I am using Java Server Faces.
public class xyz{
private List<Car> trackReportData;
public void getTrackData(){
try {
totalFuelConsumedForAllTrip = 0;
totalRefueling = 0;
totalDuration = "";
int minutes, hours;
minutes = hours = 0;
for (RefuelEventBean reb : refuelDataLog) {
totalRefueling += reb.getRefuelLiters();
}
int totalTheftLiters = 0;
for (RefuelEventBean reb : theftDataLog) {
totalTheftLiters += reb.getRefuelLiters();
System.out.println("theftDataLog recrods =" + reb.getRefuelLiters());
}
int firstVal = tripDataLog.get(0).getFuelLiter1();
int lstVal = tripDataLog.get(a).getFuelLiter2();
totalFuelConsumedForAllTrip = firstVal + totalRefueling - lstVal - totalTheftLiters;
totalFuelConsumedForAllTrip = totalFuelConsumedForAllTrip < 0 ? totalFuelConsumedForAllTrip * (-1) : totalFuelConsumedForAllTrip;
for (TripEventBean teb : tripDataLog) {
teb.setSerialNo(counterTripDue++);
tDuration += teb.getDuration();
// totalConsumedLtr += teb.getTotalFuelLiter() < 0 ? 0 : teb.getTotalFuelLiter();
// ttlRefuel += teb.getRefueling();
}
if (tDuration > 0) {
minutes = (int) (((tDuration / 1000) / 60) % 60);
hours = (int) ((tDuration / 1000) / 3600);
}
String min = minutes < 10 ? "0" + minutes : "" + minutes;
String hour = hours < 10 ? "0" + hours : "" + hours;
totalDuration = "" + hour + ":" + min;
//Start to End time
//start time:
Calendar strTime = tripDataLog.get(0).getParam1().getDateTime();
//end time
Calendar endTime = tripDataLog.get(a).getParam2().getDateTime();
//System.out.println("totalDuration" + totalDuration);
dailyTrakingReportBean.setTotalConsumedLtr(totalFuelConsumedForAllTrip);
dailyTrakingReportBean.setTotalTheftFuel(totalTheftLiters);
dailyTrakingReportBean.setTotalTrips(numberOfTrips);
dailyTrakingReportBean.setTotalDuration(totalDuration);
dailyTrakingReportBean.setTotalKmRun(totalDistance);
dailyTrakingReportBean.setStartTime(strTime);
dailyTrakingReportBean.setEndTime(endTime);
dailyTrakingReportBean.setMaxTemp(maxTemp);
dailyTrakingReportBean.setMinTemp(minTemp);
dailyTrakingReportBean.setTotalCommercialPowerOff(cpOffCounter);
dailyTrakingReportBean.setTotalRefueling(totalRefueling);
c = new Car(id, customer, vehicle, unit, dailyTrakingReportBean, param);
totalConsumedLtr = 0;
trackReportData.add(c);
dailyTrakingReportBean = new DailyTrakingReportBean();
} catch (Exception e) {
System.out.println("error in duration");
}
}
public List<Car> getTrackReportData() {
return this.trackReportData;
}
public void setTrackReportData(List<Car> trackReportData) {
this.trackReportData = trackReportData;
}
}
//another class where i am using my List:
#ManagedBean
#SessionScoped
public class abc{
#ManagedProperty(value="#{xyz}")
xyz dtb;
// private List<Car> fleetReportData;
//Kilometer Driven
private BarChartModel animatedModel1;
public abc() {
// fleetReportData = new ArrayList<>();
dtb = new DailyTrackingBean();
List<Car> fleetReportData = dtb.getTrackReportData(); //null
}
If trackReportData is initialized in the constructor with a new as per the comment (Not sure because you have not given the full code), Since you call
dailyTrakingReportBean = new DailyTrakingReportBean(); after the end of your method, it will be reinitialized to empty.
Since you are saying that you are getting null not empty there is something else happening.
Can you post the full code of a Short, Self Contained, Correct Example to figure out the problem.
I'm working on the mooc.fi assignments and I'm really stuck at the clock assignment. I don't want a solution, but advice on how to reach my solution as I'm still learning and really need to figure out how to work through this. If you're unfamiliar with mooc, the current section is on how to work with objects within objects.
It consists of three classes, the main creates the clock and the boundedcounter is what makes the clock tick. I get it to print onto the screen, but when a custom starting input is entered it prints that first, then resets the value back to zero. Can someone point me in the right direction please? Sorry for the basic question, still trying to learn this java language!
Main
public class Main {
public static void main(String[] args) {
Clock clock = new Clock(23, 59, 50);
int i = 0;
while( i < 20) {
System.out.println( clock );
clock.tick();
i++;
}
}
}
Clock
public class Clock {
private BoundedCounter hours;
private BoundedCounter minutes;
private BoundedCounter seconds;
public Clock(int hoursAtBeginning, int minutesAtBeginning, int secondsAtBeginning) {
// the counters that represent hours, minutes and seconds are created and set to have the correct initial values
this.hours = new BoundedCounter(hoursAtBeginning);
this.hours.setValue(hoursAtBeginning);
this.minutes = new BoundedCounter(minutesAtBeginning);
this.minutes.setValue(minutesAtBeginning);
this.seconds = new BoundedCounter(secondsAtBeginning);
this.seconds.setValue(secondsAtBeginning);
}
public void tick() { //increases the time
this.seconds.next();
if (this.seconds.getValue() == 0) {
this.minutes.next();
if (this.minutes.getValue() == 0) {
this.hours.next();
}
}
}
public String toString() {
// returns the string representation
return hours + ":" + minutes + ":" + seconds;
}
}
BoundedCounter
public class BoundedCounter {
private int value;
private int upperLimit;
public BoundedCounter(int upperLimit) {
// write code here
this.value = 0;
this.upperLimit = upperLimit;
}
public void next() {
// write code here
if (value < upperLimit) {
value++;
} else {
value = 0;
}
}
public int getValue() {
return value;
}
public void setValue(int value) {
if (value >= 0 && value <= upperLimit) {
this.value = value;
}
}
#Override
public String toString() {
if (value < 10) {
return "0" + value;
}
return "" + value;
}
}
You're passing the current time to BoundedCounter.
this.hours = new BoundedCounter(hoursAtBeginning);
this.minutes = new BoundedCounter(minutesAtBeginning);
this.seconds = new BoundedCounter(secondsAtBeginning);
But BoundedCounter is expecting the upper bound, not the current time.
public BoundedCounter(int upperLimit) {
Since whatever time you pass it is considered the upper limit, the next tick rolls over to 0:0:0.
BoundedCounter.next() sets value to 0 if value is not less than upperLimit. Since the Clock constructor always initializes all BoundedCounter value values to be equal to upperLimit, the first call to Clock.tick() will cause all BoundedCounter objects to set their value values to 0.
Besides the corrections:
this.hours = new BounedCounter(int upperLimit);
this.minutes = new BounedCounter(int upperLimit);
this.seconds = new BounedCounter(int upperLimit);
the method public void tick() has to be composed as shown below, otherwise when the value of the minutes is 00 while the value of the seconds is 01, 02, ...59, the value of the hours will be increased with every second, and the result will be 01:00:01, 2:00:02, 3:00:03, etc.
public void tick() {
this.seconds.next();
if (this.seconds.getValue() == 0) {
this.minutes.next();
}
if (this.minutes.getValue() == 0 && this.seconds.getValue() == 0) {
this.hours.next();
}
}
I'm a beginner/intermediate java programmer that is attempting to code something that is "out-of-my-league". The program is supposed to judge a boxing/MMA match in real time by pressing keys that correspond to different scoring values. I've figured out that I need a KeyListener, and the only way I've found to use that is with an applet.
The problem I've run into is the only cues I have to print out a score come from keyPresses and keyReleases. I want the score to print EVERY second, along with the time. I'm made a clock function and can print every second using another class with a main method, but I don't know how to do this in the applet.
Here's what I have so far:
import java.applet.Applet;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.*;
public class KeyPressTwo
extends Applet
implements KeyListener{
private long t;
private ArrayList<Integer> keysDown = new ArrayList<Integer>();
private double controlOnlyValue = 1; //Stores the score per second for control only
private double threateningValue = 2.5; //Score for threatening with strikes, i.e. landing sig strikes, or sub attempts
private double damagingValue = 4; //Score for doing significant damage and dominating hea
private static double redTotal = 0; //Stores fighter score
private static double blueTotal = 0;
private static boolean firstRun = true;
private static boolean start = false;
private static boolean releasePressed = false; //Tells KeysReleased method when to wipe keysDown list
private static long roundBeganAt = 0; //System time when the round began 5
private static String redName;
private static String blueName;
public void init(){
this.addKeyListener(this);
//If names aren't hardcoded in, get them when the program is run
if (redName == null){
redName = JOptionPane.showInputDialog("Enter the red corner fighter's name.");
blueName = JOptionPane.showInputDialog("Enter the blue corner fighter's name.");
}
}
public void paint(){
setSize(500,500);
}
#Override
public void keyPressed(KeyEvent e) {
if(!keysDown.contains(e.getKeyCode()))
keysDown.add(e.getKeyCode());
//Starts the timer, don't print anything until started
if(keysDown.contains(KeyEvent.VK_SPACE)){
start = true;
roundBeganAt = System.currentTimeMillis();
}
//If it's been more than 1s
if(nextStep()){
//If space has been pushed
if(start){
if(keysDown.contains(KeyEvent.VK_Z) || keysDown.contains(KeyEvent.VK_NUMPAD1)){
redTotal += controlOnlyValue;
}
if(keysDown.contains(KeyEvent.VK_X) || keysDown.contains(KeyEvent.VK_NUMPAD4)){
redTotal += threateningValue;
}
if(keysDown.contains(KeyEvent.VK_C) || keysDown.contains(KeyEvent.VK_NUMPAD7)){
redTotal += damagingValue;
}
if(keysDown.contains(KeyEvent.VK_COMMA) || keysDown.contains(KeyEvent.VK_NUMPAD3)){
blueTotal += controlOnlyValue;
}
if(keysDown.contains(KeyEvent.VK_M) || keysDown.contains(KeyEvent.VK_NUMPAD6)){
blueTotal += threateningValue;
}
if(keysDown.contains(KeyEvent.VK_N) || keysDown.contains(KeyEvent.VK_NUMPAD9)){
blueTotal += damagingValue;
}
System.out.print("\n" +redName +": " +redTotal +" \t" +blueName +": " +blueTotal +"\t\t" +time());
releasePressed = true;
}
}
}
//Prints time since start (e.g. 2:05)
private static String time() {
String minutes = "";
String seconds = "";
int sRaw; //Gets time directly from system, will go above 60
int s; //Gets time from sRaw, (0 - 59)
sRaw = (int)((System.currentTimeMillis() - roundBeganAt))/1000;
s = sRaw%60;
minutes = Integer.toString(sRaw/60);
if(s < 10)
seconds = "0" +Integer.toString(s);
else seconds = Integer.toString(s);
return minutes +":" +seconds;
}
//Returns true if it's been more than1s since the last time it ran
public boolean nextStep() {
if(firstRun){
t = System.currentTimeMillis();
firstRun = false;
return true;
}
if(System.currentTimeMillis() > t + 1000){
t = System.currentTimeMillis();
return true;
}else
return false;
}
public void printList(){
for(int i : keysDown)
System.out.print(i +" ");
System.out.println();
}
#Override
public void keyReleased(KeyEvent e) {
if(releasePressed){
keysDown.clear();
releasePressed = false;
}
}
#Override
public void keyTyped(KeyEvent e) {
}
}
Maybe something along these lines would work for you:
Thread timerOutputThread = new Thread(new Runnable(){
public boolean running = true;
public void run(){
output();
}
private void output(){
try {
Thread.sleep(1000);
} catch(Exception ex) {
ex.printStackTrace();
}
System.out.println("PRINT THE SCORE HERE");
if(running){
output();
}
}
});
timerOutputThread.start();
Stick that code wherever you want the Thread timer to be started, and then fill in that spot where it says "PRINT THE SCORE HERE".
I've figured out that I need a KeyListener,.."
Or preferably key bindings.
..and the only way I've found to use that is with an applet.
Where on Earth did you hear that?!? It is definitely wrong. Start using a JFrame for this app. and it will work better because focus will be more reliable.
Here is my timer class, This class is designed to constantly update a timer in a view. However, when I run the app the first toast message is displayed to the screen but the second one is never reached (the timerTask's "run" method is never executed). I know that this is probably something simple that I am doing wrong. If anyone could steer me in the right direcion that would be great.
public class MyTimer {
static Timer _timerTask = new Timer();
static int totalSeconds = 1, hour = 0, min = 0, sec = 0;
static String mTimeFormat = "%02d:%02d:%02d";
static String timeTakenString;
public static void start (){
Toast.makeText(GPSMain.context, "Message one", Toast.LENGTH_LONG).show();
TimerTask timer = new TimerTask() {
#Override
public void run() {
Toast.makeText(GPSMain.context, "Message two", Toast.LENGTH_LONG).show();
totalSeconds += 1;
sec += 1;
if(sec >= 60) {
sec = 0;
min += 1;
if (min >= 60) {
min = 0;
hour += 1;
}
}
timeTakenString = String.format(mTimeFormat, hour, min, sec);
postExecute.sendEmptyMessage(0); //update UI
}
private Handler postExecute = new Handler(){
public void dispatchMessage(Message msg) {
super.dispatchMessage(msg);
GPSMain.timer.setText("Time Taken: "+timeTakenString);
}
};
};
_timerTask.scheduleAtFixedRate(timer,1000,1000);
}
}
code in another file calling this class:
MyTimer myTimer = new MyTimer();
....
myTimer.start();
PROJECT SPEC CHANGED!
My project leader changed the spec of the project so that it no longer needs to update the timer to the UI but rather display it as an end result. Accepting the first answer anyway as it solves the original problem. Will post the new code below.
New code calls:
System.currentTimeMillis();
at the beggining and end of the runcycle, which returns a long. The first value is then subtracted from the second value to calculate the amount of time taken to execute the runcycle. That value is then manipulated and put into a timer format that is displayed at the end as a string.
public static String getTimeTaken(long end, long start){
#SuppressWarnings("unused")
String formattedTime = "", hourHour = "", hourMin = ":", minSec = ":";
long timeTaken = (end-start)/1000, hour = 0, min = 0, sec = 0;
if (timeTaken>9 ){
hourHour = "0";
hourMin = ":0";
if (timeTaken>=60){
if (timeTaken>= 3200){
hour = timeTaken/3200;
timeTaken = timeTaken%3200;
if (hour>9){
hourHour = "";
}
}
min = timeTaken/60;
timeTaken = timeTaken%60;
if (min >9){
hourMin = ":";
}
}
sec = timeTaken;
if(sec%60<10){
minSec = ":0";
}
return formattedTime = (hourHour+hour+hourMin+min+minSec+sec);
}
sec = timeTaken;
minSec = ":0";
hourMin = ":0";
hourHour = "0";
return formattedTime = (hourHour+hour+hourMin+min+minSec+sec);
}
Using thread you cant update your UI for that you have to use runOnUiThread
youractivity.this.runOnUiThread(new Runnable(){public void run(){Toast.makeText(mContext, "Message", Toast.LENGTH_LONG).show();}});
(Very late...just answering in case someone reach this question... scheduling a task doesn't garantee it will run on the proper time... it may take longer, sometimes much longer...)
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.