Method not working properly - java

This is a method that i made for my comp sci class:
public Time (int y, int x)
{
minute = x;
hour = y;
if (minute>59 || minute<0)
{
minute = 0;
}
if (hour>=24 || hour<0)
{
hour=0;
}
}
void addOne()
{//Adds one to the minute. Still in military time
minute++;
if (minute == 60) //Makes minute never exceeds 59 minutes. Hour is added 1 and minute is set to 0
{
minute = 0;
hour++;
if (hour==24)
{
hour=0;
}
}
}
public String convert()
{//Converts to standard time with am and pm
String timer = null;
int counter = 0;
if (hour<12)
{
if (hour<9)
{
if (minute>9)
{
timer = "0"+hour+":"+minute+" A.M.";
}
if (minute<10)
{
timer = "0"+hour+":0"+minute+" A.M";
}
}
if (hour>9)
{
if (minute>9)
{
timer = ""+hour+":"+minute+" A.M.";
}
if (minute<10)
{
timer = ""+hour+":0"+minute+" A.M";
}
}
}
if (hour ==12)
{
if (minute>9)
{
timer = ""+hour+":"+minute+" P.M.";
}
if (minute<10)
{
timer = ""+hour+":0"+minute+" P.M";
}
}
if (hour>12)
{
hour-=12;
if (hour ==12)
{
if (minute>9)
{
timer = ""+hour+":"+minute+" A.M.";
}
if (minute<10)
{
timer = ""+hour+":0"+minute+" A.M";
}
}
if (hour<9)
{
if (minute>9)
{
timer = "0"+hour+":"+minute+" P.M.";
}
if (minute<10)
{
timer = "0"+hour+":0"+minute+" P.M";
}
}
if (hour>9)
{
if (minute>9)
{
timer = ""+hour+":"+minute+" P.M.";
}
if (minute<10)
{
timer = ""+hour+":0"+minute+" P.M";
}
}
}
return timer;
}
And this is the code that is suppose to run:
Time time7 = new Time(23,59);
System.out.println("\ntime7: " + time7);
System.out.println("convert time7: " + time7.convert());
time7.addOne();
System.out.println("increment time7: " + time7);
System.out.println("convert time7: " + time7.convert());
I get the output as:
time7: 2359
convert time7: 11:59 P.M.
increment time7: 1200
convert time7: 12:00 P.M
But I need the output to be:
time7: 2359
convert time7: 11:59 P.M.
increment time7: 0000
convert time7: 12:00 A.M
All other parts to the program works just fine, until i get to time7.

Starting with hour set to 23, then after this code:
if (hour>12)
{
hour-=12;
...
what is the value of hour?
I'm afraid your code is needlessly complex, even if you fix the bug. Look at the String.format() method for a much better way of formatting numbers for output that does not require you to handle all those "special cases" separately.

After you increment and before you convert, you could add:
hour %= 24;
If hour is 24, it would then become 0.

Related

Java Clock Program

I am trying to make a clock program using Java, and I got everything to work properly except I cannot get the program to change the negative values to 0. I also cannot get the program to set the values of hours, minutes, and seconds to 0 if they are out of range. I have a tester program that I have to use and the T1 and T2 clock values are incorrect in my code. T1 should be 0:0:0 and T2 should be 0:0:0 as well. However, when I output my code it comes out as T1 being -3:-21:-30 and T2 is 24:60:60. I know there is something wrong with my code, but I can't find the issue, if anyone would be able to help me that would be greatly appreciated. Below is my code and then the second section is the tester code that I have to use.
public class Clock
{
// instance variables
private int hours;
private int minutes;
private int seconds;
public void setHours(int newHours) {
hours = newHours;
if (hours<0 || hours > 24) {
hours = 0;
}
}
public void setMinutes(int newMinutes) {
minutes = newMinutes;
if (minutes<0 || minutes > 60) {
minutes = 0;
}
}
public void setSeconds(int newSeconds) {
seconds = newSeconds;
if(seconds<0 || seconds > 60) {
seconds = 0;
}
}
/**
* Constructor for objects of class Clock
*/
public Clock(int newHour, int newMinute, int newSecond)
{
if (newHour > -1 || newHour < 24) {
this.hours = newHour;
}
else {
setHours(hours);
}
if (newMinute > -1 || newMinute < 60) {
this.minutes = newMinute;
}
else {
setMinutes(minutes);
}
if (newSecond > -1 || newSecond < 60) {
this.seconds = newSecond;
}
else {
setSeconds(seconds);
}
}
public int getHours() {
return hours;
}
public int getMinutes() {
return minutes;
}
public int getSeconds() {
return seconds;
}
public String toString() {
return hours + ":"+minutes+":"+seconds;
}
public void tick() {
seconds = seconds +1;
if(seconds >= 60)
{
minutes ++;
seconds = 0;
}
if(minutes >= 60)
{
hours++;
minutes = 0;
}
if(hours >=24)
{
hours = 0;
}
}
}
The next piece is the tester code.
public class ClockTest {
public static void main(String [] args){
//Create some clocks and print their times
Clock c1 = new Clock(-3,-21,-30);
System.out.println("T1: "+ c1);
c1 = new Clock(24,60,60);
System.out.println("T2: "+ c1);
c1 = new Clock(3,21,30);
System.out.println("T3: "+ c1);
//Tick the clock twice and print its time
c1.tick();
c1.tick();
System.out.println("T4: "+ c1);
c1 = new Clock(3,30,59);
c1.tick();
System.out.println("T5: "+ c1);
c1 = new Clock(3,59,59);
c1.tick();
System.out.println("T6: "+ c1);
c1 = new Clock(23,59,59);
c1.tick();
System.out.println("T7: "+ c1);
c1 = new Clock(0,0,1);
c1.tick();
System.out.println("T8: "+ c1);
c1 = new Clock(1,1,1);
c1.setHours(22);
c1.setMinutes(30);
c1.setSeconds(35);
System.out.println("T9: "+ c1);
System.out.println("T10: " + c1.getHours() + ":"
+c1.getMinutes() + ":" + c1.getSeconds());
}
}
Your condition is wrong.
When you write this:
if (newHour > -1 || newHour < 24) {
You really mean this:
if (newHour > -1 && newHour < 24) {
#nicomp is correct and you should also be using >= 24 and 60 instead of >. You might consider changing the constructor for Clock to
public Clock(int newHour, int newMinute, int newSecond) {
setHours(newHour);
setMinutes(newMinute);
setSeconds(newSecond);
}
and then do all of your validation in the set methods, instead of having some validation in the set methods and some in the constructor.

time conversion in JAVA with formula

What I want to do?
I want to return time and display based on user's input. Say, user enters in console starthour: 23 startminute: 45 duration (in min): 30 then the period for start time will be PM offcourse and you can see below I calculated the start time based on the above things, but issue is calculating the endtime. For example, in the above start times, the end time should become 00:15 with the period AM and not PM like start hour.
What I did?
public String toString(){
int h = (getHour()==0 || getHour()==12) ? getHour() : getHour()%12;
String period = (getHour()<12)? "AM" : "PM";
return String.format("%02d:%02d %s", h, getMinute(), period);
}
What to do?
The above formula calculates the start time and its period, correctly, but I need a similar formula that can calculate the endhour correctly based on start hour, start minutes and duration entered by the user.
Basically, above mentioned code needs to be manipulated to figure out the endhour, endminute and its period.
Note: Please don't tell about local time use for getting end time and period. Thankyou
EDIT: Here is what I did now:
public String toString(){
int endh = (getEndHour()==0 || getEndHour()==12) ? getEndHour() : getEndHour()%12;
String period = ((getEndHour() + duration) <12)? "AM" : "PM";
return String.format("%02d:%02d %s", endh, getEndHour(), period);
}
you should use 60 modulo for simplicity. here it is
public class Timer {
int hour;
public int getHour() {
return hour;
}
public void setHour(int hour) {
this.hour = hour;
}
public int getMinutes() {
return minutes;
}
public void setMinutes(int minutes) {
this.minutes = minutes;
}
public void addDuration(int duration) {
hour = hour + (minutes + duration)/ 60;
minutes = (minutes + duration) % 60;
}
int minutes;
#Override
public String toString() {
int h = (getHour() == 0 || getHour() == 12) ? getHour()
: getHour() % 24;
String period = (getHour() < 12) ? "AM" : "PM";
return String.format("%02d:%02d %s", h, getMinutes(), period);
}
public static void main(String args[]) {
Timer time = new Timer();
time.setHour(23);
time.setMinutes(45);
System.out.println(time.getHour());
time.addDuration(30);
System.out.println(time.getHour());
System.out.println(time);
}
}

How can I repeat the process to display the current time?

I'm trying to create a clock programm with customizable options but since I'm a beginner I'm running into some problems. I tried using the DigitalClock project but there's too many things in it for me right now
I looked into Timer and ScheduledExecuterService but I don't know how to use and where to place them.
I also tried to set a color to the background but the error was that it could be over ran.
How can I repeat the process in milliseconds, add a background and make the code lighter ?
public Clock() {
initComponents();
Calendar cal = new GregorianCalendar();
int second = cal.get(Calendar.SECOND);
int minute = cal.get(Calendar.MINUTE);
int hour = cal.get(Calendar.HOUR_OF_DAY);
/////////////////////////////////////////////////////////////
if (second < 10){
time.setText(" "+hour+": "+minute+":0"+second+"");
}
else if (minute < 10){
time.setText(" "+hour+":0"+minute+": "+second+"");
}
else if (hour < 10){
time.setText("0"+hour+": "+minute+": "+second+"");
}
else if (hour < 10 & minute < 10){
time.setText("0"+hour+":0 "+minute+": "+second+"");
}
else if (minute < 10 & second < 10){
time.setText(" "+hour+":0"+minute+":0"+second+"");
}
else if (hour < 10 & minute < 10 & second < 10){
time.setText("0"+hour+":0"+minute+":0"+second+"");
}
else {
time.setText(hour + " : " + minute + " : " + second+"");
}
////////////////////////////////////////////////////////////////
}
If you want to make it simple then you can simple do the following:
public static void main (String[] args) throws Exception
{
final SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss:SSS");
while(true) {
System.out.println(sf.format(new Date()));
Thread.sleep(1);
}
}
But this might miss a millisecond entry in between. For example, it might go directly to 310 after 308 and miss 309 in between. But since we are talking about 1/1000th of a second, in real life it is very unlikely to be noticed.
Your code will reduce to something like following:
public Clock() {
public static void main (String[] args) throws Exception {
initComponents();
final SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss:SSS");
while(true) {
time.setText = sf.format(new Date());
Thread.sleep(1);
}
}
}
final SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss:SSS");
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
System.out.println(sf.format(new Date()));
}
}, 0 , 1000000);
Will repeat in 1 ms.

Convert given time in String format to seconds in Android

Suppose time is given in MM:SS(ex- 02:30) OR HH:MM:SS in String format.how can we convert this time to second.
In your case, using your example you could use something like the following:
String time = "02:30"; //mm:ss
String[] units = time.split(":"); //will break the string up into an array
int minutes = Integer.parseInt(units[0]); //first element
int seconds = Integer.parseInt(units[1]); //second element
int duration = 60 * minutes + seconds; //add up our values
If you want to include hours just modify the code above and multiply hours by 3600 which is the number of seconds in an hour.
public class TimeToSeconds {
// given: mm:ss or hh:mm:ss or hhh:mm:ss, return number of seconds.
// bad input throws NumberFormatException.
// bad includes: "", null, :50, 5:-4
public static long parseTime(String str) throws NumberFormatException {
if (str == null)
throw new NumberFormatException("parseTimeString null str");
if (str.isEmpty())
throw new NumberFormatException("parseTimeString empty str");
int h = 0;
int m, s;
String units[] = str.split(":");
assert (units.length == 2 || units.length == 3);
switch (units.length) {
case 2:
// mm:ss
m = Integer.parseInt(units[0]);
s = Integer.parseInt(units[1]);
break;
case 3:
// hh:mm:ss
h = Integer.parseInt(units[0]);
m = Integer.parseInt(units[1]);
s = Integer.parseInt(units[2]);
break;
default:
throw new NumberFormatException("parseTimeString failed:" + str);
}
if (m<0 || m>60 || s<0 || s>60 || h<0)
throw new NumberFormatException("parseTimeString range error:" + str);
return h * 3600 + m * 60 + s;
}
// given time string (hours:minutes:seconds, or mm:ss, return number of seconds.
public static long parseTimeStringToSeconds(String str) {
try {
return parseTime(str);
} catch (NumberFormatException nfe) {
return 0;
}
}
}
import org.junit.Test;
import static org.junit.Assert.*;
public class TimeToSecondsTest {
#Test
public void parseTimeStringToSeconds() {
assertEquals(TimeToSeconds.parseTimeStringToSeconds("1:00"), 60);
assertEquals(TimeToSeconds.parseTimeStringToSeconds("00:55"), 55);
assertEquals(TimeToSeconds.parseTimeStringToSeconds("5:55"), 5 * 60 + 55);
assertEquals(TimeToSeconds.parseTimeStringToSeconds(""), 0);
assertEquals(TimeToSeconds.parseTimeStringToSeconds("6:01:05"), 6 * 3600 + 1*60 + 5);
}
#Test
public void parseTime() {
// make sure all these tests fail.
String fails[] = {null, "", "abc", ":::", "A:B:C", "1:2:3:4", "1:99", "1:99:05", ":50", "-4:32", "-99:-2:4", "2.2:30"};
for (String t: fails)
{
try {
long seconds = TimeToSeconds.parseTime(t);
assertFalse("FAIL: Expected failure:"+t+" got "+seconds, true);
} catch (NumberFormatException nfe)
{
assertNotNull(nfe);
assertTrue(nfe instanceof NumberFormatException);
// expected this nfe.
}
}
}
}
int v = 0;
for (var x: t.split(":")) {
v = v * 60 + new Byte(x);
}
This snippet should support HH:MM:SS (v would result in seconds) or HH:MM (v would be in minutes)
try this
hours = totalSecs / 3600;
minutes = (totalSecs % 3600) / 60;
seconds = totalSecs % 60;
timeString = String.format("%02d",seconds);
private static final String TIME_FORMAT = "hh:mm a";//give whatever format you want.
//Function calling
long timeInMillis = TimeUtils.getCurrentTimeInMillis("04:21 PM");
long seconds = timeInMillis/1000;
//Util Function
public static long getCurrentTimeInMillis(String time) {
SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT, Locale.getDefault());
// sdf.setTimeZone(TimeZone.getTimeZone("GMT")); //getting exact milliseconds at GMT
// sdf.setTimeZone(TimeZone.getDefault());
Date date = null;
try {
date = sdf.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
return date.getTime();
}
I have written an extension function in Kotlin for converting String to seconds
fun String?.converTimeToSeconds(): Int {
if (this.isNullOrEmpty().not()) {
val units = this?.split(":")?.toTypedArray()
if (units?.isNotEmpty() == true && units.size >= 3) {
val hours = units[0].toInt()
val minutes = units[1].toInt()
val seconds = units[2].toInt()
return (3660 * hours) + (60 * minutes) + seconds
}
}
return 0
}

How to sum minutes in array if their format is string?

I have an string array that includes some minutes like "00:05", "00:30", "00:25" etc. I want to sum the values as time format? Can anyone help me how do I do this?
Total time in minutes:
int sum = 0;
final String[] mins = new String[] { "00:05", "00:30", "00:25" };
for (String str : mins) {
String[] parts = str.split(":");
sum += Integer.parseInt(parts[1]);
}
System.out.println(sum);
You don't specify exactly how you want this output formatted.
If there may be hour elements as well, then replace the second line of the loop with this:
sum += (Integer.parseInt(parts[0]) * 60) + Integer.parseInt(parts[1]);
I'll go for quick and dirty
Split each String on the ":"
Convert both parts to integer
Multiply the first time by 60 to convert hours to minutes, and add the second part
Do this for each value in your array, and count them together
This results in the total time in minutes, which you can convert to whatever format you like
You could substring it, and then call Integer.parseInt on the result. For the hours part, do the same and multiply it by 60.
Split the strings on ':', pars the values as ints and add 'em up.
this is my suggestion. Neither compiled, ran, tested, nor guaranteed.
long seconds = 0;
for ( String min : minutes )
{
seconds += Integer.parseInt(min.substring(0,1))*60 + Integer.parseInt(min.substring(3,4));
}
return new Date ( seconds / 1000 ) ;
An object oriented approach:
public static TimeAcumm sum(final String[] times) {
final TimeAcumm c = new TimeAcumm();
for (final String time : times) {
c.incrementFromFormattedString(time);
}
return c;
}
public class TimeAcumm {
private int hours = 0;
private int minutes = 0;
private int seconds = 0;
public int getHours() {
return hours;
}
public int getMinutes() {
return minutes;
}
public int getSeconds() {
return seconds;
}
public void incrementFromFormattedString(final String time) {
final String[] parts = time.split(":");
this.minutes += Integer.parseInt(parts[0]);
this.seconds += Integer.parseInt(parts[1]);
validate();
}
private void validate() {
if (this.minutes > 59) {
this.hours++;
this.minutes -= 60;
}
if (this.seconds > 59) {
this.minutes++;
this.seconds -= 60;
}
}
#Override
public String toString() {
final String s = hours + "H:" + minutes + "M:" + seconds + "S";
return s;
}
}

Categories

Resources