How do I get the military time difference to read correctly? - java

I am trying to write a program in which the console tells a person the difference between two times WITHOUT IF STATEMENTS, in "military time" or 24 hr time. So far, I have:
import java.util.Scanner;
public class MilTimeDiff {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the first time: ");
String time1 = s.next();
System.out.print("Enter the second time: ");
String time2 = s.next();
String tm1 = String.format("%02d", Integer.parseInt(time1));
String tm2 = String.format("%02d", Integer.parseInt(time2));
int t1 = Integer.parseInt(tm1);
int t2 = Integer.parseInt(tm2);
int difference = t2 - t1;
while (t1 < t2) {
String tmDif = Integer.toString(difference);
System.out.println("The difference between times is " + tmDif.substring(0, 1) + " hours " +
tmDif.substring(1) + " minutes.");
break;
}
}
}
But I have two issues: one: if I make time one 0800, and time two 1700, it gives me the correct 9 hours. But if the difference is 10 hours or more, it gives 1 hour and a lot of minutes. I thought using the String.format method would help, but it doesn't do anything.
two: I'm not sure how to approach a situation where time 1 is later than time 2.
Thanks!

You can try below code which will give Time difference in military format :
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the first time: ");
String time1 = s.next();
System.out.print("Enter the second time: ");
String time2 = s.next();
String tm1 = String.format("%02d", Integer.parseInt(time1));
String tm2 = String.format("%02d", Integer.parseInt(time2));
String hrs1 = time1.substring(0, 2);
String min1 = time1.substring(2, 4);
String hrs2 = time2.substring(0, 2);
String min2 = time2.substring(2, 4);
// int difference = t2 - t1;
if (Integer.parseInt(time1) < Integer.parseInt(time2)) {
int minDiff = Integer.parseInt(min2) - Integer.parseInt(min1);
int hrsDiff = Integer.parseInt(hrs2) - Integer.parseInt(hrs1);
if (minDiff < 0) {
minDiff += 60;
hrsDiff--;
}
System.out.println("The difference between times is " + hrsDiff + " hours " + minDiff + " minutes.");
} else {
int minDiff = Integer.parseInt(min1) - Integer.parseInt(min2);
int hrsDiff = Integer.parseInt(hrs1) - Integer.parseInt(hrs2);
if (minDiff < 0) {
minDiff += 60;
hrsDiff--;
}
System.out.println("The difference between times is " + hrsDiff + " hours " + minDiff + " minutes.");
}
}

Related

java- how to add time properly?

My code isn't working properly for example when a user put that right now is 5 h 43 m and 7 s and the user wanna add 3 h 50 m and 57 s the code compute and shows what will be the time adding but it shows 8 h 93 m and 64 s but I want that after 60 m it shows 9 h 34 m and 4 s so can u help me out.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner user_input = new Scanner (System.in);
int startup_hour;
int startup_minute;
int startup_second;
int add_hours;
int add_minutes;
int add_seconds;
System.out.print("what time is it right now(hour)? \n");
startup_hour = user_input.nextInt();
System.out.print("what time is it right now(minutes? \n");
startup_minute = user_input.nextInt();
System.out.print("what time is it right now(seconds)? \n");
startup_second = user_input.nextInt();
System.out.println("The starting time is " + startup_hour
+ " hours " + startup_minute + " minutes " + "and "
+ startup_second + " seconds \n");
System.out.print("How many hours you wanna add? \n");
add_hours = user_input.nextInt();
System.out.print("How many minutes you wanna add? \n");
add_minutes = user_input.nextInt();
System.out.print("How many seconds you wanna add? \n");
add_seconds = user_input.nextInt();
System.out.println("The user wanna add " + add_hours
+ " hours " + add_minutes + " minutes "
+ "and " + add_seconds + " seconds \n");
int totalHours = (startup_hour + add_hours);
int totalMinutes = (startup_minute + add_minutes);
int totalSeconds = (startup_second + add_seconds);
if (totalSeconds == 60){
totalMinutes++;
totalSeconds = 0;
}
if (totalMinutes == 60){
totalHours++;
totalMinutes = 0;
}
System.out.println("After adding, the time would then be "
+ totalHours + " hours " + totalMinutes + " Minutes "
+ totalSeconds + " Seconds ");
*emphasized text*
}
}
thanku
The reason your program is not working because you are processing time, without using the standard unit, which is seconds.
For example:
Suppose the start up time is 1 hours 3 minutes and 57 seconds.
And the user want to add, 1 hour 57 minutes and 3 seconds.
The correct answer will be, 3 hours 1 Minutes 0 Seconds but your program will return 2 hours 61 Minutes 0 Seconds.
Now, why did this happen?
The reason are:
As already stated, you did not process time using the standard unit (seconds).
The condition in your if loop is not correct. You are only checking if the minutes/seconds are equal to 60. What if the minutes or seconds are 61 or more?
Solution:
The simplest solution is, first convert time into seconds, add how much time you want to add, then convert it back to hours:minutes:seconds. You won't even have to use if loop if you process time using seconds.
Here is the modified code, which works properly :
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
Scanner user_input = new Scanner(System.in);
int startup_hour;
int startup_minute;
int startup_second;
int add_hours;
int add_minutes;
int add_seconds;
System.out.print("What time is it right now(hour) : ");
startup_hour = user_input.nextInt();
System.out.print("What time is it right now(minutes) : ");
startup_minute = user_input.nextInt();
System.out.print("What time is it right now(seconds) : ");
startup_second = user_input.nextInt();
System.out.println("The starting time is " + startup_hour + " hours " + startup_minute + " minutes "
+ "and " + startup_second + " seconds.");
System.out.println();
System.out.print("How many hours you wanna add : ");
add_hours = user_input.nextInt();
System.out.print("How many minutes you wanna add : ");
add_minutes = user_input.nextInt();
System.out.print("How many seconds you wanna add : ");
add_seconds = user_input.nextInt();
System.out.println("The user wanna add " + add_hours + " hours " + add_minutes + " minutes "
+ "and " + add_seconds + " seconds.");
System.out.println();
int totalSecondsAtStart = (startup_hour * 60 * 60) + (startup_minute * 60) + startup_second;
int totalSecondsToAdd = (add_hours * 60 * 60) + (add_minutes * 60) + (add_seconds);
int totalSeconds = totalSecondsAtStart + totalSecondsToAdd;
//Convert total seconds to hour, minutes and seconds;
int totalMinutes = (totalSeconds / 60);
int totalHours = (totalMinutes / 60);
int finalHours = totalHours;
int finalMinutes = totalMinutes - (totalHours * 60);
int finalSeconds = totalSeconds - (totalMinutes * 60);
System.out.println("After adding, the time would then be " + finalHours + " hours"
+ " " + finalMinutes + " Minutes " + finalSeconds + " Seconds.");
}
}
Notice how I converted time back into hours:minutes:seconds.

How to get an input word in the output? Beginning Java

I am trying to get the departure place in my out put but I am confused on how to do it. Do I have to declare it in the String method at the top?
int seconds1;
int seconds2;
int minutes;
int hours;
Scanner sc = new Scanner(System.in);
System.out.println("Enter departure city: ");
String departure = sc.nextLine();
System.out.println("Enter arrival city ");
String arrival = sc.nextLine();
System.out.println("Enter time (in seconds) it takes to travel between: ");
seconds1 = sc.nextInt();
hours = (seconds1 % 86400) / 3600;
minutes = ((seconds1 % 86400) % 3600) / 60;
seconds2 = ((seconds1 % 86400) % 3600) % 60;
// I am trying to get this to say "The time between + departure + and + arrival+is"
System.out.println("The time to travel between and is ");
System.out.println(hours + " : " + minutes + " : " + seconds2);
}
}
You would have this:
System.out.println("The time to travel between " + departure + " and " + arrival + " is ");
Please take a look-
package com.jap.falcon;
import java.util.Scanner;
public class Problem2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int seconds1;
int seconds2;
int minutes;
int hours;
System.out.println("Enter departure city: ");
String departure = sc.nextLine();
System.out.println("Enter arrival city ");
String arrival = sc.nextLine();
System.out.println("Enter time (in seconds) it takes to travel between: ");
seconds1 = sc.nextInt();
hours = (seconds1 % 86400) / 3600;
minutes = ((seconds1 % 86400) % 3600) / 60;
seconds2 = ((seconds1 % 86400) % 3600) % 60;
System.out.println("The time to travel between "+ departure +" and "+arrival+" is "); // I am trying to get this to say "The time between
// + departure + and + arrival + is"
System.out.println(hours + " : " + minutes + " : " + seconds2);
}
}
You can specify the departure and arrival variables in System.out.println() as shown in the below code:
System.out.println("The time to travel between"+departure +" and"+arrival +" is ");
What you're asking about is called concatenation.
As a baseline, concatenation is when you do the "addition" of Strings.
String a = "Hello, " + "World!";
System.out.println(a); // Prints "Hello, World!"
This can also be done within the print statement.
System.out.println("Hello, " + "World!");
Since your departure location and destination are both already in the form of strings, it could look like this:
System.out.println("The time between " + departure + " and " + arrival + " is:");
To Java, your departure and arrival variables are already strings, so it will just insert them between your pre-typed strings. Don't forget to have spaces included in the strings (after "between", on either side of "and", and before "is". Hope this helps!
add this line:
System.out.println("The time between " + departure + " and " + arrival + " is");
whole code:
import java.util.Scanner;
public class Problem2 {
public static void main( String [] args) {
Scanner sc = new Scanner(System.in);
int seconds1;
int seconds2;
int minutes;
int hours;
System.out.println("Enter departure city: ");
String departure = sc.nextLine();
System.out.println("Enter arrival city ");
String arrival = sc.nextLine();
System.out.println("Enter time (in seconds) it takes to travel between: ");
seconds1 = sc.nextInt();
hours = (seconds1 % 86400) / 3600;
minutes = ((seconds1 % 86400) % 3600) / 60;
seconds2 = ((seconds1 % 86400) % 3600) % 60;
System.out.println("The time between " + departure + " and " + arrival + " is"); // I am trying to get this to say "The time between + departure + and + arrival + is"
System.out.println(hours + " : " + minutes + " : " + seconds2);
} }

Java - Variables are not updating

I'm relatively new to programming and I am currently trying to complete one of my tutorial's for uni. The point of the tutorial is to set 8 primitive data types, print them, then reassign a new value and print those. The issue I have is when I reassign value of the variable it still prints the original value. My code is as follows:
import javax.swing.JOptionPane;
public class week02tutorial02 {
public static void main(String[] args) {
byte element = 63 ;
short speed = 1192 ;
int age = 10;
long tfn = 987_654_321 ;
float height = 161.5f ;
double weight = 80.4 ;
boolean alive = true ;
char firstinitial = 'C';
String tutorial = "Favourite element: " +element+"\n"
+ "Running Speed: "+speed+"kph\n"
+ "Age: "+age+"\n"
+ "Tax File Number: "+tfn+"\n"
+ "Height: "+height+"cm\n"
+ "Weight: "+weight+"Kg\n"
+ "Still Alive: "+alive+"\n"
+ "First Initial: "+firstinitial+"\n";
JOptionPane.showMessageDialog(null, tutorial);
element = 20;
speed = 512;
age = 15;
tfn = 563_435_123;
height = 120.3f;
weight = 56.8;
alive = false;
firstinitial = 'D';
JOptionPane.showMessageDialog(null, tutorial);
}
}
You were super close. You need to make sure when you update your values, you also update your tutorial string. Your sting only takes copies of the value you originally gave it. So change the original and the copy doesn't know.
This should work.
import javax.swing.JOptionPane;
public class week02tutorial02 {
public static void main(String[] args) {
byte element = 63 ;
short speed = 1192 ;
int age = 10;
long tfn = 987_654_321 ;
float height = 161.5f ;
double weight = 80.4 ;
boolean alive = true ;
char firstinitial = 'C';
String tutorial = "Favourite element: " +element+"\n"
+ "Running Speed: "+speed+"kph\n"
+ "Age: "+age+"\n"
+ "Tax File Number: "+tfn+"\n"
+ "Height: "+height+"cm\n"
+ "Weight: "+weight+"Kg\n"
+ "Still Alive: "+alive+"\n"
+ "First Initial: "+firstinitial+"\n";
JOptionPane.showMessageDialog(null, tutorial);
element = 20;
speed = 512;
age = 15;
tfn = 563_435_123;
height = 120.3f;
weight = 56.8;
alive = false;
firstinitial = 'D';
//new line to update tutorials values
tutorial = "Favourite element: " +element+"\n"
+ "Running Speed: "+speed+"kph\n"
+ "Age: "+age+"\n"
+ "Tax File Number: "+tfn+"\n"
+ "Height: "+height+"cm\n"
+ "Weight: "+weight+"Kg\n"
+ "Still Alive: "+alive+"\n"
+ "First Initial: "+firstinitial+"\n";
JOptionPane.showMessageDialog(null, tutorial);
}
}

Java if/for loop assistance

Below is my code...I am trying to make a countdown timer. Right now it works correctly in terms of counting down in the correct sequential order. I am trying to figure out how to place an if statement within the code so that is prints 1 minute and ''seconds, instead of 1 minutes and '' seconds
import java.util.Scanner;
public class countdown {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int minutes;
System.out.println("Please enter the timer countdown in minutes:");
minutes = scan.nextInt();
while (minutes < 1) {
System.out.print("Invalid entry: Enter 1 or more minutes: ");
minutes = scan.nextInt();
}
for (int i = minutes - 1; i >= 0; i--)
{
for (int s = 59; s >= 1; s--)
System.out.println(i + " minutes, " + s + " seconds");
System.out.println("The timer is done!");
}
}
}
Like this,
String minutes = i + (i > 1 ? " minutes" : " minute"); // put this line in outer loop
String seconds = s + (s > 1 ? " seconds" : " second"); // and this line in inner loop
System.out.println(minutes +", "+ seconds);
just add an if/else statement in there:
for (int i = minutes - 1; i >= 0; i--){
String minute;
if(minutes == 1)
minute = " minute ";
else
minute = " minutes ";
for (int s = 59; s >= 1; s--){
String seconds;
if(s == 1)
seconds = " second";
else
seconds = " second";
System.out.println(i + minute + s + seconds);
}
}
The other answer is probably better, but it uses a different syntax that makes all this code into a short line. They do basically the same thing.
These two if/else statements should work.
for (int s = 59; s >= 1; s--)
{
if (i == 1)
System.out.print(i + " minute, ");
else
System.out.print(i + " minutes, ");
if (s == 1)
System.out.println(s + " second");
else
System.out.println(s + " seconds");
}

Java: convert seconds into day, hour, minute and seconds using TimeUnit

I am using TimeStamp class to convert seconds into Day,Hours,Minutes,Seconds. I used following code
public static void calculateTime(long seconds) {
int day = (int)TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) - TimeUnit.SECONDS.toHours(TimeUnit.SECONDS.toDays(seconds));
long minute = TimeUnit.SECONDS.toMinutes(seconds) - TimeUnit.SECONDS.toMinutes(TimeUnit.SECONDS.toHours(seconds));
long second = TimeUnit.SECONDS.toSeconds(seconds) - TimeUnit.SECONDS.toSeconds(TimeUnit.SECONDS.toMinutes(seconds));
System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}
But I am not getting right result.
For example when I called this method as calculateTime(3600) it gives me the result as Day 0 Hour 1 Minute 60 Seconds 3540 instead of Day 0 Hour 1 Minute 0 Seconds 0.
What is the wrong with my logic? Please help me.
It should be like
int day = (int)TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);
EDIT
Explanation:
Day calculation is correct, it does not require explanation.
TimeUnit.SECONDS.toHours(seconds) will give you direct conversion from seconds to hours without consideration for days you have already calculated. Minus the hours for days you already got i.e, day*24. You now got remaining hours.
Same for minute and second. You need to minus the already got hour and minutes respectively.
You can do like this to only use TimeUnit:
public static void calculateTime(long seconds) {
int day = (int) TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) -
TimeUnit.DAYS.toHours(day);
long minute = TimeUnit.SECONDS.toMinutes(seconds) -
TimeUnit.DAYS.toMinutes(day) -
TimeUnit.HOURS.toMinutes(hours);
long second = TimeUnit.SECONDS.toSeconds(seconds) -
TimeUnit.DAYS.toSeconds(day) -
TimeUnit.HOURS.toSeconds(hours) -
TimeUnit.MINUTES.toSeconds(minute);
System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}
or the slightly shorter but maybe not as intuitive
public static void calculateTime(long seconds) {
int day = (int) TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) -
TimeUnit.DAYS.toHours(day);
long minute = TimeUnit.SECONDS.toMinutes(seconds) -
TimeUnit.HOURS.toMinutes(TimeUnit.SECONDS.toHours(seconds));
long second = TimeUnit.SECONDS.toSeconds(seconds) -
TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(seconds));
System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}
Simple method:
public static void calculateTime(long seconds) {
long sec = seconds % 60;
long minutes = seconds % 3600 / 60;
long hours = seconds % 86400 / 3600;
long days = seconds / 86400;
System.out.println("Day " + days + " Hour " + hours + " Minute " + minutes + " Seconds " + sec);
}
Here is a code i created : (For 3600 seconds it shows "Days:0 Hours:1 Minutes:0 Seconds:0")
public class TimeConvert
{
public static void main(String[] args)
{
int fsec,d,h,m,s,temp=0,i;
fsec=3600;
//For Days
if(fsec>=86400)
{
temp=fsec/86400;
d=temp;
for(i=1;i<=temp;i++)
{
fsec-=86400;
}
}
else
{
d=0;
}
//For Hours
if(fsec>=3600)
{
temp=fsec/3600;
h=temp;
for(i=1;i<=temp;i++)
{
fsec-=3600;
}
}
else
{
h=0;
}
//For Minutes
if(fsec>=60)
{
temp=fsec/60;
m=temp;
for(i=1;i<=temp;i++)
{
fsec-=60;
}
}
else
{
m=0;
}
//For Seconds
if(fsec>=1)
{
s=fsec;
}
else
{
s=0;
}
System.out.println("Days:"+d+" Hours:"+h+" Minutes:"+m+" Seconds:"+s);
}
}
Hope it answers your question.
Late but helpful
get time in the format 00:00:00
/**
* The time in format.
*
* in The Format of 00:00:00
*/
public String getTimeInFormat(long _SECONDS)
{
if(TimeUnit.SECONDS.toHours(_SECONDS)>0)
{
return String.format("%02d:%02d:%02d",
TimeUnit.SECONDS.toHours(_SECONDS),
TimeUnit.SECONDS.toMinutes(_SECONDS) -
TimeUnit.HOURS.toMinutes(TimeUnit.SECONDS.toHours(_SECONDS)),
TimeUnit.SECONDS.toSeconds(_SECONDS) -
TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(_SECONDS)));
}
else {
return String.format("%02d:%02d",
TimeUnit.SECONDS.toMinutes(_SECONDS) -
TimeUnit.HOURS.toMinutes(TimeUnit.SECONDS.toHours(_SECONDS)),
TimeUnit.SECONDS.toSeconds(_SECONDS) -
TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(_SECONDS)));
}
}
Try this
public static void calculateTime(long seconds) {
int day = (int)TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) ;
long tempSec = seconds - (TimeUnit.HOURS.toSeconds(hours) );
System.out.println("after hours calculation "+ tempSec);
long minute = TimeUnit.SECONDS.toMinutes(tempSec);
if(tempSec > TimeUnit.MINUTES.toSeconds(minute)){
tempSec = tempSec - (TimeUnit.MINUTES.toSeconds(minute) );
}else{
tempSec = TimeUnit.MINUTES.toSeconds(minute) - tempSec;
}
System.out.println("after min calculation "+ tempSec);
long second = TimeUnit.SECONDS.toSeconds(tempSec) ;
System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}
This is my code:
public static String secondsToString(TimeUnit greatestUnit, long sourceDuration, TimeUnit sourceUnit) {
int ordinal = greatestUnit.ordinal();
if(ordinal<=sourceUnit.ordinal())
return String.format("%02d", sourceDuration);
final long greatestDuration = greatestUnit.convert(sourceDuration, sourceUnit);
final long rest = sourceDuration - sourceUnit.convert(greatestDuration, greatestUnit);
return String.format("%02d:", greatestDuration) + secondsToString(TimeUnit.values()[--ordinal], rest, sourceUnit);
}
or by loop
public static String secondsToStringByLoop(TimeUnit greatestUnit, long sourceDuration, TimeUnit sourceUnit) {
final StringBuffer sb = new StringBuffer();
int ordinal = greatestUnit.ordinal();
while(true){
if(ordinal<=sourceUnit.ordinal()) {
sb.append(String.format("%02d", sourceDuration));
break;
}
final long greatestDuration = greatestUnit.convert(sourceDuration, sourceUnit);
// if(greatestDuration>0 || sb.length()>0)
sb.append(String.format("%02d:", greatestDuration));
sourceDuration -= sourceUnit.convert(greatestDuration, greatestUnit);
greatestUnit = TimeUnit.values()[--ordinal];
};
return sb.toString();
}
usage example:
String str = secondsToString(TimeUnit.DAYS, 1000, TimeUnit.SECONDS);
function returns: "00:00:16:40" (days:hours:minutes:seconds)
str = UnitsConverter.secondsToString(TimeUnit.DAYS, 1000, TimeUnit.MINUTES);
returns: "00:16:40" (days:hours:minutes)
str = UnitsConverter.secondsToString(TimeUnit.MINUTES, 1000, TimeUnit.SECONDS);
returns: "16:40" (minutes:seconds)
public static void timeCalculator(){
Scanner input = new Scanner(System.in);
System.out.print("Enter length of time in seconds: ");
int n = input.nextInt();
int nDay = n/86400;
int nHours = (n%86400)/3600;
int nMin = ((n%86400)%3600) /60;
int nSec =(((n%86400)%3600)%60);
System.out.println();
System.out.print("That is "+ nDay+ " day(s),"+nHours+" hour(s), "+nMin+" minute(s), and "+nSec+" second(s). ");
}

Categories