Showing Morning, afternoon, evening, night message based on Time in java - java

What i am trying to do::
Show message based on
Good morning (12am-12pm)
Good after noon (12pm -4pm)
Good evening (4pm to 9pm)
Good night ( 9pm to 6am)
CODE::
I used 24-hr format to get this logic
private void getTimeFromAndroid() {
Date dt = new Date();
int hours = dt.getHours();
int min = dt.getMinutes();
if(hours>=1 || hours<=12){
Toast.makeText(this, "Good Morning", Toast.LENGTH_SHORT).show();
}else if(hours>=12 || hours<=16){
Toast.makeText(this, "Good Afternoon", Toast.LENGTH_SHORT).show();
}else if(hours>=16 || hours<=21){
Toast.makeText(this, "Good Evening", Toast.LENGTH_SHORT).show();
}else if(hours>=21 || hours<=24){
Toast.makeText(this, "Good Night", Toast.LENGTH_SHORT).show();
}
}
Question:
Is this this best way of doing it, If no which is the best way

You should be doing something like:
Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
if(timeOfDay >= 0 && timeOfDay < 12){
Toast.makeText(this, "Good Morning", Toast.LENGTH_SHORT).show();
}else if(timeOfDay >= 12 && timeOfDay < 16){
Toast.makeText(this, "Good Afternoon", Toast.LENGTH_SHORT).show();
}else if(timeOfDay >= 16 && timeOfDay < 21){
Toast.makeText(this, "Good Evening", Toast.LENGTH_SHORT).show();
}else if(timeOfDay >= 21 && timeOfDay < 24){
Toast.makeText(this, "Good Night", Toast.LENGTH_SHORT).show();
}

For anyone who is looking for the latest Kotlin syntax for #SMA's answer, here is the helper function :
fun getGreetingMessage():String{
val c = Calendar.getInstance()
val timeOfDay = c.get(Calendar.HOUR_OF_DAY)
return when (timeOfDay) {
in 0..11 -> "Good Morning"
in 12..15 -> "Good Afternoon"
in 16..20 -> "Good Evening"
in 21..23 -> "Good Night"
else -> "Hello"
}
}

I would shorten your if/elseif statement to:
String greeting = null;
if(hours>=1 && hours<=12){
greeting = "Good Morning";
} else if(hours>=12 && hours<=16){
greeting = "Good Afternoon";
} else if(hours>=16 && hours<=21){
greeting = "Good Evening";
} else if(hours>=21 && hours<=24){
greeting = "Good Night";
}
Toast.makeText(this, greeting, Toast.LENGTH_SHORT).show();

java.time
I would advise to use Java 8 LocalTime.
Maybe create a class like this to handle your time of day problem.
public class GreetingMaker { // think of a better name then this.
private static final LocalTime MORNING = LocalTime.of(0, 0, 0);
private static final LocalTime AFTER_NOON = LocalTime.of(12, 0, 0);
private static final LocalTime EVENING = LocalTime.of(16, 0, 0);
private static final LocalTime NIGHT = LocalTime.of(21, 0, 0);
private LocalTime now;
public GreetingMaker(LocalTime now) {
this.now = now;
}
public void printTimeOfDay() { // or return String in your case
if (between(MORNING, AFTER_NOON)) {
System.out.println("Good Morning");
} else if (between(AFTER_NOON, EVENING)) {
System.out.println("Good Afternoon");
} else if (between(EVENING, NIGHT)) {
System.out.println("Good Evening");
} else {
System.out.println("Good Night");
}
}
private boolean between(LocalTime start, LocalTime end) {
return (!now.isBefore(start)) && now.isBefore(end);
}
}

try this code(get hours and get minute methods in Date class are deprecated.)
private void getTimeFromAndroid() {
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
int hours = c.get(Calendar.HOUR_OF_DAY);
int min = c.get(Calendar.MINUTE);
if(hours>=1 && hours<=12){
Toast.makeText(this, "Good Morning", Toast.LENGTH_SHORT).show();
}else if(hours>=12 && hours<=16){
Toast.makeText(this, "Good Afternoon", Toast.LENGTH_SHORT).show();
}else if(hours>=16 && hours<=21){
Toast.makeText(this, "Good Evening", Toast.LENGTH_SHORT).show();
}else if(hours>=21 && hours<=24){
Toast.makeText(this, "Good Night", Toast.LENGTH_SHORT).show();
}
}

You determine if it is in the first interval, and then all other intervals depends on the upper limit. So you can make it even shorter:
String greeting = null;
if(hours>=1 && hours<=11){
greeting = "Good Morning";
} else if(hours<=15){
greeting = "Good Afternoon";
} else if(hours<=20){
greeting = "Good Evening";
} else if(hours<=24){
greeting = "Good Night";
}
Toast.makeText(this, greeting, Toast.LENGTH_SHORT).show();

Using Time4J (or Time4A on Android) enables following solutions which do not need any if-else-statements:
ChronoFormatter<PlainTime> parser =
ChronoFormatter.ofTimePattern("hh:mm a", PatternType.CLDR, Locale.ENGLISH);
PlainTime time = parser.parse("10:05 AM");
Map<PlainTime, String> table = new HashMap<>();
table.put(PlainTime.of(1), "Good Morning");
table.put(PlainTime.of(12), "Good Afternoon");
table.put(PlainTime.of(16), "Good Evening");
table.put(PlainTime.of(21), "Good Night");
ChronoFormatter<PlainTime> customPrinter=
ChronoFormatter
.setUp(PlainTime.axis(), Locale.ENGLISH)
.addDayPeriod(table)
.build();
System.out.println(customPrinter.format(time)); // Good Morning
There is also another pattern-based way to let the locale decide in a standard way based on CLDR-data how to format the clock time:
ChronoFormatter<PlainTime> parser =
ChronoFormatter.ofTimePattern("hh:mm a", PatternType.CLDR, Locale.ENGLISH);
PlainTime time = parser.parse("10:05 AM");
ChronoFormatter<PlainTime> printer1 =
ChronoFormatter.ofTimePattern("hh:mm B", PatternType.CLDR, Locale.ENGLISH);
System.out.println(printer1.format(time)); // 10:05 in the morning
ChronoFormatter<PlainTime> printer2 =
ChronoFormatter.ofTimePattern("B", PatternType.CLDR, Locale.ENGLISH)
.with(Attributes.OUTPUT_CONTEXT, OutputContext.STANDALONE);
System.out.println(printer2.format(time)); // morning
The only other library known to me which can also do this (but in an awkward way) is ICU4J.

You can equally have a class that returns the greetings.
import java.util.Calendar;
public class Greetings {
public static String getGreetings()
{
Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
if(timeOfDay < 12){
return "Good morning";
}else if(timeOfDay < 16){
return "Good afternoon";
}else if(timeOfDay < 21){
return "Good evening";
}else {
return "Good night";
}
}
}

For Kotlin Users They can use it like this :
private fun showDayMessage():String {
val c: Calendar = Calendar.getInstance()
var message:String ?=null
val timeOfDay: Int = c.get(Calendar.HOUR_OF_DAY)
if (timeOfDay >= 0 && timeOfDay < 12) {
message = "Good Morning"
} else if (timeOfDay >= 12 && timeOfDay < 16) {
message = "Good Afternoon"
} else if (timeOfDay >= 16 && timeOfDay < 21) {
message = "Good Evening"
} else if (timeOfDay >= 21 && timeOfDay < 24) {
message = "Good Night"
}
return message!!
}

When I write
Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
I didn't get output and it doesn't show any error. Just the timeOfDay won't get assigned any value in the code. I felt it was because of some threading while Calendar.getInstance() is executed. But when I collapsed the lines it worked for me. See the following code:
int timeOfDay = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
if(timeOfDay >= 0 && timeOfDay < 12){
greeting.setText("Good Morning");
}else if(timeOfDay >= 12 && timeOfDay < 16){
greeting.setText("Good Afternoon");
}else if(timeOfDay >= 16 && timeOfDay < 21){
greeting.setText("Good Evening");
}else if(timeOfDay >= 21 && timeOfDay < 24){
greeting.setText("Good Morning");
}

private String getStringFromMilli(long millis) {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(millis);
int hours = c.get(Calendar.HOUR_OF_DAY);
if(hours >= 1 && hours <= 12){
return "MORNING";
}else if(hours >= 12 && hours <= 16){
return "AFTERNOON";
}else if(hours >= 16 && hours <= 21){
return "EVENING";
}else if(hours >= 21 && hours <= 24){
return "NIGHT";
}
return null;
}

If somebody looking the same for Dart and Flutter: the code without if statements - easy to read and edit.
main() {
int hourValue = DateTime.now().hour;
print(checkDayPeriod(hourValue));
}
String checkDayPeriod(int hour) {
int _res = 21;
Map<int, String> dayPeriods = {
0: 'Good night',
12: 'Good morning',
16: 'Good afternoon',
21: 'Good evening',
};
dayPeriods.forEach(
(key, value) {
if (hour < key && key <= _res) _res = key;
},
);
return dayPeriods[_res];
}

using System;
namespace PF_Claas_Assign1
{
class Program
{
static void Main(string[] args)
{
DateTime Greeting = DateTime.Now;
if (Greeting.Hour >= 5 && Greeting.Hour < 12)
{
Console.WriteLine("Good morning....!");
}
else if (Greeting.Hour >= 12 && Greeting.Hour < 16)
{
Console.WriteLine("Good afternoon...!");
}
else if (Greeting.Hour >= 16 && Greeting.Hour < 20)
{
Console.WriteLine("Good evening...!");
}
else
{
Console.WriteLine("Good night...!");
}
}
}
}

In kotlin use the following
fun getCurrentTime(dateFormatInPut:String,myDate:String): Time {
val sdf = SimpleDateFormat(dateFormatInPut, Locale.ENGLISH)
val date = sdf.parse(myDate)
val millis = date!!.time
val calendar=Calendar.getInstance()
calendar.timeInMillis=millis
return when (calendar.get(Calendar.HOUR_OF_DAY)) {
in 0..11 -> Time.Morning
in 12..15 -> Time.AfterNoon
else -> Time.Evening
}
}
Here Time is enum class
enum class Time {
Morning,
AfterNoon,
Evening
}

A cleaner method for detecting date would be.
//the time cannot go below zero, so if this case is true, it must be between 0 and 12
if(time <= 12)
{
return "Good Morning";
//it will only fall into this case if the time is greater than 12.
}else if(time < 16)
{
return "Good Afternoon";
}else if(time < 21)
{
return "Good Evening";
}else //it is guaranteed that the time will not exceed 24
//, and if the previous case are all false, it must be within 21 and 24
{
return "Good Night";
}

More specific
public static String getDayMessage() {
Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
if (timeOfDay < 5) {
return "Hi, Good Mid Night";
}else if (timeOfDay < 6) {
return "Hi, Good Late Night";
} else if (timeOfDay < 12) {
return "Hi, Good Morning";
} else if (timeOfDay < 14) {
return "Hi, Good Noon";
} else if (timeOfDay < 16) {
return "Hi, Good Afternoon";
} else if (timeOfDay < 21) {
return "Hi, Good Evening";
} else {
return "Hi, Good Night";
}
}

As Simple as possible
private String getTimeFromAndroid() {
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
int hours = c.get(Calendar.HOUR_OF_DAY);
int min = c.get(Calendar.MINUTE);
if(hours<=12){
return "Good Morning";
}else if(hours<=16){
return "Good Afternoon";
}else if(hours<=21){
return "Good Evening";
}else {
return "Good Night";
}
}

This solution seems perfect for the tropics area countries' users. Suppose my country is Bangladesh and this greeting is appropriate for our users most of the time.
public static String getTimeToHumanGenericTerm(boolean isBangla, Calendar c) {
int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
if (timeOfDay < 5) {
return isBangla ? " মধ্যরাত " : " Mid Night";
} else if (timeOfDay < 6) {
return isBangla ? " শেষরাত " : " Late Night";
} else if (timeOfDay < 12) {
return isBangla ? " সকাল " : " Late Night";
} else if (timeOfDay < 14) {
return isBangla ? " দুপুর" : " Noon";
} else if (timeOfDay < 16) {
return isBangla ? " বিকাল" : " Afternoon";
} else if (timeOfDay < 21) {
return isBangla ? " সন্ধ্যা" : " Evening";
} else {
return isBangla ? " রাত " : " Night";
}
}

Related

Getting a return line error for my method?

public static boolean isValidDate(int month, int day) {
if (month >= 3 && month <= 5) {
if (month == 3) {
if (day >= 1 && day <= 31) {
return true;
} else {
return false;
}
} else if (month == 4) {
if (day >= 1 && day <= 30) {
return true;
} else {
return false;
}
} else if (month == 5) {
if (day >= 1 && day <= 15) {
return true;
} else {
return false;
}
}
} else {
return false;
}
}
Get these errors:not sure how to fix them im returning everything.
BoxOffice.java:81: error: missing return statement
}
BoxOffice.java:85: error: missing return statement
}
The compiler isn't smart enough to deduce that the inner if covers every scenario in the range of the outer if. Just change
else if(month == 5) {
to
else { // month must be 5 here
shmosel's answer describes the problem and the least disruptive fix.
Personally, I'd write this as a switch, and avoid writing the long if/else statements to check the day:
switch (month) {
case 3:
return (day >= 1 && day <= 31);
case 4:
return (day >= 1 && day <= 30);
case 5:
return (day >= 1 && day <= 15);
default:
return false;
}
you need to transforme the else if (month == 5) to else ....
public static boolean isValidDate(int month, int day)
{
if (month >= 3 && month <= 5)
{
if (month == 3)
{
if (day >= 1 && day <= 31)
{
return true;
}
else
{
return false;
}
}
else if (month == 4)
{
if (day >= 1 && day <= 30)
{
return true;
}
else
{
return false;
}
}
else
{
if (day >= 1 && day <= 15)
{
return true;
}
else
{
return false;
}
}
}
else
{
return false;
}
}
Try making a boolean, and instead of returning in the if statement, change the boolean and return at the end of the method. Here is an example with your code.
public static boolean isValidDate (int month, int day) {
boolean result = true; //This must be set to a value to avoid compiler errors
if(month >= 3 && month <= 5) {
if(month == 3) {
if(day >= 1 && day <= 31) {
result = true;
}
else {
result = false;
}
}
else if(month == 4) {
if(day >= 1 && day <= 30) {
result = true;
}
else {
result = false;
}
}
else if(month == 5) {
if(day >= 1 && day <= 15) {
result = true;
}
else {
result = false;
}
}
}
else {
result = false;
}
return result;
}
Hope that helps!

Malfunctioning java.util.Calendar in Android

Having a difficult time with learning Android programming, though I suspect that the problem isn't necessarily Android itself. I am attempting to make a (toggleable) auto-silencer, setting the phone to vibrate once school starts and to regular mode once it ends. It also must not force this; i.e. it only changes it once per change in time (e.g. if I set the phone to vibrate while outside of school hours, it won't change it back the next minute). Here's my code:
public class TimeBroadcastReceiver extends BroadcastReceiver {
boolean previousState;
#Override
public void onReceive(Context context, Intent intent) {
Calendar now = GregorianCalendar.getInstance();
int day = now.get(Calendar.DAY_OF_WEEK);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
AudioManager manager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
switch (day) {
case Calendar.MONDAY:
if (((hour == 7 && minute >= 40) || hour >= 7) && ((hour == 13 && minute <= 45) || hour <= 13)) {
if (!previousState) {
manager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
previousState = true;
}
} else {
if (previousState) {
manager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
previousState = false;
}
}
return;
case Calendar.TUESDAY:
case Calendar.WEDNESDAY:
case Calendar.THURSDAY:
case Calendar.FRIDAY:
if (((hour == 7 && minute >= 30) || hour >= 7) && ((hour == 14 && minute <= 40) || hour <= 14)) {
if (!previousState) {
manager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
previousState = true;
}
} else {
if (previousState) {
manager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
previousState = false;
}
}
return;
}
}
}
Against all logic, or at least I hope against simple boolean logic, the ringer disables itself at 7:00 AM exactly (rather than 7:40 on Mondays and 7:30 on other days), and re-enables itself at 2PM exactly on Mondays (rather than 1:45) and 3PM exactly on other days (rather than 2:40). I simply do not know how it could produce this result. Thoughts?
Also, registration code in case it matters:
TimeBroadcastReceiver receiver = new TimeBroadcastReceiver();
IntentFilter filter = new IntentFilter();
{
filter.addAction(Intent.ACTION_TIME_TICK);
}
public void setEnabled(boolean enabled) {
if (!this.enabled && enabled) {
registerReceiver(receiver, filter);
this.enabled = true;
} else if (this.enabled && !enabled) {
unregisterReceiver(receiver);
this.enabled = false;
}
}
This is called from a service.

Wheel of Fortune: building string

I am working on code for an assignment in which I have to make Wheel of Fortune, I am having trouble with building the string that will be shown to the user after each guess. I have the wheel spin working but I just can't seem to figure how to build the string. I can also answer any questions about this if you have any. Any help will be much appreciated. Here is my code so far:
class WheelOfFortune3 {
public static void main(String[] args) {
int result, location, newLocation, numGuess = 0;
String puzzle, guess;
String sub[] = new String[26];
for (int i = 0; i < sub.length; i++) {
sub[i] = "_";
}
result = wheelResult();
System.out.println("You spun $" + result);
puzzle = getPuzzle();
System.out.println(puzzle);
do {
guess = In.getString();
location = checkGuess(puzzle, guess);
if (location == -1) {
System.out.println("Incorrect guess");
}
if (location >= 0 && location <= 25) {
System.out.println("Correct guess");
newLocation = location + 1;
sub[numGuess] = puzzle.substring(location, newLocation);
for (int i = 0; i <= 10; i++) {
System.out.print(sub[i] + " ");
}
System.out.println("");
numGuess = numGuess + 1;
System.out.println(numGuess);
System.out.println(sub.length);
}
}
while (numGuess < sub.length);
}
public static int checkGuess(String puzzle, String guess) {
String word = puzzle;
int location;
location = word.indexOf(guess);
return location;
}
public static int wheelResult() {
int result;
int[] wheelSpin = new int[1];
wheelSpin[0] = (int)(24 * Math.random());
if (wheelSpin[0] == 1 || wheelSpin[0] == 18 || wheelSpin[0] == 22) {
result = 200;
return result;
} else if (wheelSpin[0] == 2 || wheelSpin[0] == 5) {
result = 900;
return result;
} else if (wheelSpin[0] == 0 || wheelSpin[0] == 3 || wheelSpin[0] == 15) {
result = 250;
return result;
} else if (wheelSpin[0] == 4 || wheelSpin[0] == 6 || wheelSpin[0] == 12 || wheelSpin[0] == 16) {
result = 300;
return result;
} else if (wheelSpin[0] == 7) {
result = 1500;
return result;
} else if (wheelSpin[0] == 9 || wheelSpin[0] == 11) {
result = 700;
return result;
} else if (wheelSpin[0] == 10 || wheelSpin[0] == 14 || wheelSpin[0] == 21) {
result = 500;
return result;
} else if (wheelSpin[0] == 13) {
result = 5000;
return result;
} else if (wheelSpin[0] == 23 || wheelSpin[0] == 19) {
result = 600;
return result;
} else if (wheelSpin[0] == 8 || wheelSpin[0] == 20) {
result = 100;
return result;
} else if (wheelSpin[0] == 17) {
result = 17;
return result;
}
return -1;
}
public static String getPuzzle() {
String puzzle;
//a long ride
return "A long ride";
//01234567890
}
}
This can be done using a List of Characters and the .contains() method like so:
List<Character> guessedCharacters = new ArrayList<>();
each time a player guesses a letter, add that letter to
the guessedCharacters List like this: guessedCharacters.add(char);
Then you can do something like this to generate the String to output to the player:
StringBuilder toShowSB = new StringBuilder();
for(int i=0,n=puzzle.length;i<n;i++){
if(guessedCharacters.contains(puzzle.charAt(i))){
toShowSB.append(puzzel.charAt(i));
}else{
toShowSB.append("_");
}
}
String toShow = toShowSB.toString();
This will create a String that holds all of the guessed letters in their places and an underscore denoting characters that have not been properly guessed yet.

How to optimize a lot of switch cases?

How could I optimize having a lot of switch cases? Is there some other method to do what I'm attempting to do?
I have a time slider and this slider updates a variable currentTime with the value (1-24) where the current slider is and calls the updateTime() method. In this method I have switch cases for 1 - 24 (only 3 in this example). Instead of making 24 switch cases, could I do this in a much simpler way?
private void updateTime() {
switch (currentTime) {
case 1:
hourlyData = weatherAPI.HourlyReport(1);
setHourlyData();
break;
case 2:
hourlyData = weatherAPI.HourlyReport(2);
setHourlyData();
break;
...
case 24:
hourlyData = weatherAPI.HourlyReport(24);
setHourlyData();
break;
default:
System.out.println("Oops");
break;
}
}
--
public Map HourlyReport(int hour) {
Hourly hourly = new Hourly(fio);
//In case there is no hourly data available
if (hourly.hours() < 0) {
System.out.println("No hourly data.");
} else {
hourlyData.put("Temp", hourly.getHour(hour).temperature()); // Temperature
hourlyData.put("TempFeel", hourly.getHour(hour).apparentTemperature()); // Feel Temperature
hourlyData.put("Humidity", hourly.getHour(hour).humidity()); // Humidity
hourlyData.put("WindSpeed", hourly.getHour(hour).windSpeed()); // Wind Speed
hourlyData.put("Precip", hourly.getHour(hour).precipProbability()); // Precipitation
hourlyData.put("TimeStamp", hourly.getHour(hour).time());// TimeStamp
}
return hourlyData;
}
The use of a switch is not justified in this case. Use a simple if
if (currentTime > 0 && currentTime < 25) {
hourlyData = weatherAPI.HourlyReport(currentTime);
setHourlyData();
} else {
System.out.println("Oops");
}
I would validate first
private void updateTime() {
if (currentTime < 1 || currentTime > 24)
throw new IllegalStateException("currentTime: " + currentTime);
hourlyData = weatherAPI.HourlyReport(currentTime);
setHourlyData();
}
You could use a simple if statement to validate currentTime's value and just pass it to weatherAPI.HourlyReport:
private void updateTime() {
if (currentTime >= 1 || currentTime <= 24) {
hourlyData = weatherAPI.HourlyReport(currentTime);
setHourlyData();
} else{
System.out.println("Oops");
}
}
private boolean isValidHour(){
if (currentTime >= 1 && currentTime <= 24)
return true;
else
return false;
}
private void updateTime() {
if(this.isValidHour())
hourlyData = weatherAPI.HourlyReport(currentTime);
else
System.out.println("Oops");
}

Countdown timer with GUI using SwingWorker - not updating properly

i'm trying to make a countdown timer using swingworker, problem is when seconds get to zero, programs sets them back to 60 and deducts one.I did make the program without GUI and it works just perfect, but using swingworker my timer looks like this
1: 0: 2
1: 0: 1
0: 59: 60
which is kinda wrong and should be
1: 0: 1
1: 0: 0
0: 59: 59
Both of my class lie on the same logic.I guess it has something to do with sending the whole Time object to the 'process' but i just can't explain it to myself.
doInBackground() method :
protected Void doInBackground() throws Exception {
Integer hours = Integer.parseInt(hoursField.getText());
Integer minutes = Integer.parseInt(minutesField.getText());
Integer seconds = Integer.parseInt(secondsField.getText());
Time time = new Time(hours, minutes, seconds);
if(minutes < 59 & seconds < 59) {
if(hours >=0 & minutes >=0 & seconds >=0) {
boolean count = true;
while(count) {
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
Logger.getLogger(Chronometer.class.getName()).log(Level.SEVERE, null, e);
}
time.setSeconds(time.getSeconds() - 1);
publish(time);
if(time.getHours() == 0 & time.getMinutes() == 0 & time.getSeconds() == 0) {
count = false;
}
if(time.getSeconds() == 0) {
time.setSeconds(60);
if(time.getMinutes() != 0) {
time.setMinutes((time.getMinutes() - 1));
}else if(time.getMinutes() == 0) {
time.setHours((time.getHours() - 1));
if(time.getHours() >= 0) {
time.setMinutes(59);
}
if(time.getHours() < 0) {
time.setHours(0);
}
}
}
}
}else {
System.exit(0);
}
}
return null;
}
And this is the simple java class that works on the same logic :
boolean count = true;
while(count) {
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
}
seconds--;
System.out.println(hours + ": " + minutes + ": " + seconds);
if(hours == 0 & minutes == 0 & seconds == 0) {
count = false;
}
if(seconds == 0) {
seconds = 60;
if(minutes != 0){
minutes--;
}else if(minutes == 0) {
hours--;
if(hours >=0){
minutes = 59;
}
if(hours < 0) {
hours = 0;
}
}
}
}
If anyone could point me my mistake, i'd be very grateful.
Thanks
Adding process method
public void process(List<Time> time) {
for(Time t : time) {
showField.setText(String.valueOf(t.getHours()) + ": " + String.valueOf(t.getMinutes())+ ": " + String.valueOf(t.getSeconds()));
}
}
your line
if(time.getSeconds() == 0) time.setSeconds(60);
needs to be
if(time.getSeconds() == 0) time.setSeconds(59);
And invert this tow lines:
time.setSeconds(time.getSeconds() - 1);
publish(time);
like this:
publish(time);
time.setSeconds(time.getSeconds() - 1);
The deduction is correct but it's not showing the result because when seconds reaches cero the conditional it's executed, not showing the intermediate time.
Change this line:
if(time.getSeconds() == 0)
for this one:
if(time.getSeconds() < 0)
And this:
if(time.getHours() == 0 & time.getMinutes() == 0 & time.getSeconds() == 0)
if(time.getHours() == 0 & time.getMinutes() == 0 & time.getSeconds() < 0)
I did not dig at your logic, but you can achieve the same using Calendar which looks more simple.
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hours);
c.set(Calendar.MINUTE, minutes);
c.set(Calendar.SECOND, seconds);
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date d = c.getTime();
System.out.println(format.format(d));
while(count) {
c.set(Calendar.SECOND, c.get(Calendar.SECOND)-1); //decrement 1 second at a time
d = c.getTime();
System.out.println(format.format(d));
Thread.sleep(1000); //Pause for a second between each print
}
I have used SimpleDateFormat("HH:mm:ss") for simplicity. If you need different fields of time, then you can use Calendar.get(..) method to get the same

Categories

Resources