Time Zone Formula - java

I am making a practice where i need to calculate the hour based on a difference of time zone so i basically came up with the following code:
System.out.print("What is the time difference, in hours, between your home and your destination? ");
Scanner input = new Scanner(System.in);
int hoursDif = input.nextInt();
input.nextLine();
int mid;
if (hoursDif < 0){
mid = 24 + hoursDif;
}
else{
mid = hoursDif;
}
int noon;
if (hoursDif+12 < 24){
noon = hoursDif + 12;
}
else{
noon = hoursDif + 12 +- 24;
}
System.out.print("That means that when it is midnight at home it will be " + mid + ":00 and noon: " + noon);
But the problem is that the course is only beginning and havent see loops yet, so anyone knows if there is a way to get the same output but without the if statements?

This is pretty simple with a proper LocalDateTime object.
System.out.print("What is the time difference, in hours, between your home and your destination? ");
Scanner input = new Scanner(System.in);
int hoursDif = input.nextInt();
LocalDateTime localDateTime = LocalDateTime.now();
int mid = localDateTime.truncatedTo(ChronoUnit.DAYS).plusHours(hoursDif).getHour();
int noon = localDateTime.truncatedTo(ChronoUnit.DAYS).plusHours(12).plusHours(hoursDif).getHour();
System.out.print("That means that when it is midnight at home it will be " + mid + ":00 and noon: " + noon);
You just get the current time, truncate it to DAYS (so it's 00:00:00) and then add the time you entered.

Related

Why is my code is outputing thousands of times?

I am supposed to make this code output Day total and then the number of hours worked for that day. The code is currently displaying the day and the total. But it is displaying too many times for the program to even register. For instance, it asks to input a day, and I'll put in Monday. Then the number of hours worked, and I'll put 6. It will then output Monday 6.0 thousands of times. The expected output should be Day Total 6. What am I missing or is added to cause this?
// SuperMarket.java - This program creates a report that lists weekly hours worked
// by employees of a supermarket. The report lists total hours for
// each day of one week.
// Input: Interactive
// Output: Report.
import java.util.Scanner;
public class SuperMarket
{
public static void main(String args[])
{
// Declare variables.
final String HEAD1 = "WEEKLY HOURS WORKED";
final String DAY_FOOTER = " Day Total "; // Leading spaces are intentional.
final String SENTINEL = "done"; // Named constant for sentinel value.
double hoursWorked = 0; // Current record hours.
String hoursWorkedString = ""; // String version of hours
String dayOfWeek; // Current record day of week.
double hoursTotal = 0; // Hours total for a day.
String prevDay = ""; // Previous day of week.
boolean done = false; // loop control
Scanner input = new Scanner(System.in);
// Print two blank lines.
System.out.println();
System.out.println();
// Print heading.
System.out.println(HEAD1);
// Print two blank lines.
System.out.println();
System.out.println();
// Read first record
System.out.println("Enter day of week or done to quit: ");
dayOfWeek = input.nextLine();
if(dayOfWeek.compareTo(SENTINEL) == 0)
done = true;
else
{
System.out.print("Enter hours worked: ");
hoursWorkedString = input.nextLine();
hoursWorked = Integer.parseInt(hoursWorkedString);
prevDay = dayOfWeek;
}
while(done == false)
{
System.out.println(dayOfWeek + " " + hoursWorked);
hoursTotal = 0;
prevDay = hoursWorkedString;
}
System.out.println(dayOfWeek + " " + hoursWorked + hoursTotal);
hoursTotal++;
if(dayOfWeek.compareTo(SENTINEL) == 0)
{
hoursWorked = dayOfWeek.compareTo(SENTINEL);
prevDay = dayOfWeek;
done = true;
}
else
done = false;
// Include work done in the dayChange() method
if(dayOfWeek.compareTo(SENTINEL) == 0)
System.out.println(DAY_FOOTER + hoursTotal);
System.exit(0);
} // End of main() method.
} // End of SuperMarket class.
while(done == false)
{
System.out.println(dayOfWeek + " " + hoursWorked);
hoursTotal = 0;
prevDay = hoursWorkedString;
}
In this code block, you aren't changing done variable, so it is an infinite loop.

Cost Calculator

My code needs to calculate the cost of ISP service via 3 different questions.
choice of package (1,2,3)
Which month it is: (1-12)
How many hours used:(x)
I broke the months into 3 separate arrays. One for Feb. with 28 days, one for months with 30 days and one with months that have 31 days. I need to check the number of hours entered and make sure that it does not exceed the amount of hours that are in whichever month they have chosen. I have started to with this:
import java.util.Scanner; //Needed for the scanner class
public class ISP_Cost_Calc
{
public static void main(String[] args)
{
String input; //To hold users input.
char selectPackage; //To hold Internet Package
double hourUsage, totalCharges, addCharges; //Variables
Scanner keyboard = new Scanner(System.in); //Create a Scanner object to collect keyboard input.
int[] twentyeightArray; //List of months with 28 days (that's what the te is for)
twentyeightArray = new int[1]; //Make room for one integer in list
twentyeightArray[0] = 2; //Set the one integer in this list to month number 2
int[] thirtyArray; //List of months with 30 days.
thirtyArray = new int[4];
thirtyArray[0] = 4;
thirtyArray[1] = 6;
thirtyArray[2] = 9;
thirtyArray[3] = 11;
int[] thiryoneArray; //List of months with 31 days.
thiryoneArray = new int[7];
thiryoneArray[0] = 1;
thiryoneArray[1] = 3;
thiryoneArray[2] = 5;
thiryoneArray[3] = 7;
thiryoneArray[4] = 8;
thiryoneArray[5] = 10;
thiryoneArray[6] = 12;
//Prompt the user to select a Internet Package.
System.out.print("Enter your plan (1, 2, 3):");
input = keyboard.nextLine();
selectPackage = input.charAt(0);
//Prompt the user for the month.
System.out.print("Enter your month number (1-12):");
input = keyboard.nextLine();
char monthNum = input.charAt(0);
//Prompt the user for how many hours used.
System.out.print("Enter your hours:");
input = keyboard.nextLine();
hourUsage = Double.parseDouble(input);
//Display pricing for selected package...
switch (selectPackage)
{
case '1':
if (hourUsage > 10)
{
addCharges = hourUsage - 10;
totalCharges = (addCharges * 2.0) + 9.95;
System.out.println("You have used " + hourUsage + " hours and your total is $" + totalCharges + " per month. ");
}
else
{
System.out.println("Your total is $9.95 per month.");
}
break;
case '2':
if (hourUsage > 20 )
{
addCharges = hourUsage - 20;
totalCharges = (addCharges * 1.0) + 13.95;
System.out.println("You have used " + hourUsage + " and your total is $" + totalCharges + " per month.");
}
else
{
System.out.println("Your total is $13.95 per month.");
}
break;
case '3':
System.out.println("Your total is $19.95 per month.");
break;
default:
System.out.println("Invalid Choice.");
}
}
}
So I just need advice with how to incorporate this into my if statements.
Thank you
Instead of using separate arrays to implement your month. You can do this:
int[] month = {31,28,31,30,31,30,31,31,30,31,30,31};
int[] monthLeapYear = {31,29,31,30,31,30,31,31,30,31,30,31};
You can check whether a given year is a leap year first, then choose the right array to use for the month. This way you only need 2 arrays - ever.
and you may have something like this to help you. I also advise you to create some methods in your implementation to modularize your program.
public static Boolean isLeapYear(int year)
{
if(year % 4 == 0 && year % 100 != 0)
return true;
return false;
}
The array is by index 0 - 11. That be can be over come by doing this:
//Let say your current month is 1-12
month[currentMonth-1]
Alternatively add 1 element to your array (so that the elements tally now):
int[] month = {0,31,28,31,30,31,30,31,31,30,31,30,31};
It may be easier if instead of using seperatre arrays for different numbers of days, you use an enum of Months which contains the number of days and the number of hours.
public enum Month {
JANUARY(31),FEBRUARY(28),MARCH(31),APRIL(30),MAY(31),JUNE(30),JULY(31),AUGUST(30),SEPTEMBER(30),OCTOBER(31),
NOVEMBER(30),DECEMBER(31);
private int hours;
private Month(int days){
hours = days*24;
}
public int getHours(){
return hours;
}
}
Using something like that would cut down on the unnecessary array use and combine everything into a single class. This would make it a lot easier to get the number of days and hours in each month.
Instead of creating multiple arrays, just use one array like:
month[0] = 31;
month[1] = 28;//what if leap year?
month[2] = 31;
//and so on
Then you could do something like:
int monthNumber = monthNum - 48;
if (hours > month[monthNumber - 1] * 24) {
//do something
} else {
//else do another thing
}
This is insane.
What is going to happen in 2016 when February will have 29 days instead of 28 days?
Stop using integers to represent hours. Use proper data types like DateTime and TimeSpan.
Get the DateTime at 00:00 of the 1st day of the selected month,
then get the DateTime at 00:00 of the 1st day of the next month,
then calculate the difference of these two to obtain a TimeSpan holding the duration of the selected month.
Then convert your hours to a TimeSpan and compare this against the duration of the selected month.
This will tell you whether the entered number of hours fits within the selected month.
To check conditions based on your months.You can use contains method of arraylist by converting array into arraylist as
Arrays.asList(your1stArray).contains(yourChar)
in your char just add the input no of the month
for eg:
switch (monthNum )
{
case '1':
if (Arrays.asList(your1stArray).contains(yourChar)){
//code goes here
}
case '1':
if (Arrays.asList(your2ndArray).contains(yourChar)){
//code goes here
}
)
)

How do I repeat an entire program until manually terminated? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
My code works fine except for the part where I am supposed to ask the user if they would like to quit the program. It's a simple y/n that should trigger the entire program to repeat if 'n' is entered and terminates when 'y' is entered. I know i need to use a while loop but i just can't figure out exactly how I need to write it in code so that it works like expected.
import java.util.*;
public class MilitaryTime
{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
int hour1, minute1, hour2, minute2;
System.out.print("Please enter the first time: ");
int time1 = in.nextInt();
System.out.println();
hour1 = time1 / 100;
minute1 = time1 % 100;
System.out.print("Please enter the second time: ");
int time2 = in.nextInt();
System.out.println();
hour2 = time2 / 100;
minute2 = time2 % 100;
System.out.println("Time elapsed: " + (Math.abs(hour1 - hour2) + " Hours, " + (Math.abs(minute1 - minute2) + " Minutes \n")));
System.out.print("Do you want to quit? (y/n): ");
String answer = in.next();
while (answer != "n")
{
}
}
}
You should probably split your code in (at least) two different methods, but I'll just try to point out a way to achieve what you want with minimal changes:
public static void main (String [] args)
{
String answer = null; // you have no answer yet...
do { // ... but you want to execute your stuff at least once
Scanner in = new Scanner(System.in);
int hour1, minute1, hour2, minute2;
System.out.print("Please enter the first time: ");
int time1 = in.nextInt();
System.out.println();
hour1 = time1 / 100;
minute1 = time1 % 100;
System.out.print("Please enter the second time: ");
int time2 = in.nextInt();
System.out.println();
hour2 = time2 / 100;
minute2 = time2 % 100;
System.out.println("Time elapsed: " + (Math.abs(hour1 - hour2) + " Hours, " + (Math.abs(minute1 - minute2) + " Minutes \n")));
System.out.print("Do you want to quit? (y/n): ");
answer = in.next();
} while (!answer.equalsIgnoreCase("n"));
}
Until then rerun the main method.
while (answer.equals("n")) // comment by drewmoore; its helpfull for strings..
{
// you said, program should repeat if n is pressed.
// so, if answer is equal to n then execute the main function.
main();
}
This would execute until the user presses some other button.
Secondly, you don't need to use while loop. This can be done using if too.

Java code to determine number of days elapsed does not return correct answer

The problem with this code is that it does calculate the days alive only for some birth dates. I tried using different birth dates and testing it with an online calculator and it seems not all are correct. I think the problem is because of Leapyears, more and less than 30 days in a month.
public class DaysAlive {
public static void main (String [] args){
Scanner userInput = new Scanner(System.in);
int TodayYear, TodayMonth, TodayDay;
int YearBorn, MonthBorn, DayBorn;
int DaysAlive;
System.out.println("Enter today's date");
System.out.print ("Year: ");
TodayYear = userInput.nextInt ();
System.out.print ("Month: ");
TodayMonth = userInput.nextInt ();
System.out.print ("Day: ");
TodayDay = userInput.nextInt ();
System.out.println("Enter date of birth");
System.out.print ("Year: ");
YearBorn = userInput.nextInt ();
System.out.print ("Month: ");
MonthBorn = userInput.nextInt ();
System.out.print ("Day: ");
DayBorn = userInput.nextInt ();
//I think this line is the problem
DaysAlive = (TodayYear - YearBorn) *365 + (TodayMonth - MonthBorn) *30 +(TodayDay - DayBorn);
System.out.println("DaysAlive: " + DaysAlive);
}
}
How about using Calendar? It will do all of that for you... or joda time library
check it out here:
Getting the number of days between two dates in java
If I understand what you want, you should be able to use something like this -
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Enter today's date");
System.out.print("Year: ");
int todayYear = userInput.nextInt();
System.out.print("Month: ");
int todayMonth = userInput.nextInt();
System.out.print("Day: ");
int todayDay = userInput.nextInt();
// Java has January as month 0. Let's not require that the user know.
Calendar today = new GregorianCalendar(todayYear, todayMonth - 1,
todayDay);
System.out.println("Enter date of birth");
System.out.print("Year: ");
int yearBorn = userInput.nextInt();
System.out.print("Month: ");
int monthBorn = userInput.nextInt();
System.out.print("Day: ");
int dayBorn = userInput.nextInt();
Calendar born = new GregorianCalendar(yearBorn, monthBorn - 1, dayBorn);
double diff = today.getTimeInMillis() - born.getTimeInMillis();
diff = diff / (24 * 60 * 60 * 1000); // hours in a day, minutes in a hour,
// seconds in a minute, millis in a
// second.
System.out.println(Math.round(diff));
}
With output
Enter today's date
Year: 2014
Month: 03
Day: 14
Enter date of birth
Year: 2014
Month: 03
Day: 13
1
You are right, the problem is that not all months have 30 days in them. A simple solution would to be use if statements and make another integer variable called something like monthMultiplier. As other people pointed out you can also use the Calendar
if(TodayMonth == 9 || TodayMonth == 11 || TodayMonth == 4 || TodayMonth == 6) {
monthMultiplier = 30;//30 days in these months
}
if(TodayMonth == 2){
monthMultiplier = 28;//WELL 28.25 accounting for leap years
}
else {
monthMultiplier = 31;
}
DaysAlive = (TodayYear - YearBorn) *365 + (TodayMonth - MonthBorn) * monthMultiplier +(TodayDay - DayBorn);
Joda-Time
The Joda-Time library makes easy work of this problem. Just one line of code, basically. Joda-Time handles time zones, leap days, and other issues.
Hand-coding such date-time work is risky, error-prone, and frankly silly given the excellent libraries available (Joda-Time and the new java.time package in Java 8).
Example Code
Here’s some example code in Joda-Time 2.3.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime start = new DateTime(2008, 4, 26, 0, 0, 0, timeZone);
DateTime stop = new DateTime(2008, 5, 26, 0, 0, 0, timeZone);
int daysBetween = Days.daysBetween( start, stop ).getDays();
Dump to console…
System.out.println( "start: " + start );
System.out.println( "stop: " + stop );
System.out.println( "daysBetween: " + daysBetween );
When executed…
start: 2008-04-26T00:00:00.000+02:00
stop: 2008-05-26T00:00:00.000+02:00
daysBetween: 30

Java class - add n hours, minutes, and seconds to a time

I am fairly new to Java would like to know if this logic looks sound. The purpose of this class is to receive input from the user for a time in 12-hour format. Then the user is prompted to input a period of time. Finally, it outputs the final time (with the time added), in 12-hour format. I've run several tests scenarios through this and everything seems to be working fine. I'd just like some additional sets of trained eyes to look at it before I call it good. Thanks for your help!
import javax.swing.JOptionPane;
public class M3E7 {
public static void main(String args[]) {
String start_hr = null;
String start_min = null;
String start_sec = null;
String abbr = null;
String hr = null;
String min = null;
String sec = null;
int start_hr_num = 0;
int start_min_num = 0;
int start_sec_num = 0;
int hr_num = 0;
int min_num = 0;
int sec_num = 0;
int final_hr = 0;
int final_min = 0;
int final_sec = 0;
start_hr = JOptionPane.showInputDialog("Start time - Enter the hours.");
start_min = JOptionPane.showInputDialog("Start time - Enter the minutes.");
start_sec = JOptionPane.showInputDialog("Start time - Enter the seconds.");
abbr = JOptionPane.showInputDialog("Start time - Enter either am or pm.");
hr = JOptionPane.showInputDialog("Enter the number of hours to add (less than 24).");
min = JOptionPane.showInputDialog("Enter the number of minutes to add (less than 60).");
sec = JOptionPane.showInputDialog("Enter the number of seconds to add (less than 60).");
start_hr_num = Integer.parseInt(start_hr);
start_min_num = Integer.parseInt(start_min);
start_sec_num = Integer.parseInt(start_sec);
hr_num = Integer.parseInt(hr);
min_num = Integer.parseInt(min);
sec_num = Integer.parseInt(sec);
if (abbr.equals("pm")); {
start_hr_num += 12;
}
final_hr = (start_hr_num + hr_num);
final_min = (start_min_num + min_num);
final_sec = (start_sec_num + sec_num);
if (final_sec >= 60) {
final_min++;
final_sec -= 60;
}
if (final_min >= 60) {
final_hr++;
final_min -= 60;
}
if (final_hr >= 24) {
final_hr -= 24;
}
if (final_hr > 12) {
final_hr -= 12;
abbr.equals("pm");
}
else if (final_hr == 12) {
final_hr -= 12;
abbr.equals("am");
}
else {
abbr.equals("am");
}
JOptionPane.showMessageDialog(null, "The new time of day is " + final_hr + ":" + final_min + ":" + final_sec + " " + abbr);
System.exit(0);
}
}
Do yourself a favour and don't perform date/time arithmetic yourself.
Instead, use Joda Time to handle it for you:
Parse the first input as a LocalTime (via DateTimeFormatter.parseLocalTime)
Parse the next three inputs as Period values using Period.hours(), Period.minutes() and Period.seconds()
Use LocalTime.plus(ReadablePeriod) to add the period to the time
Format and output as you wish
Since it is homework, I don't want to give you the entire answer written up, but at least give you something to think about.
All times and dates are stored as milliseconds from epoch (ie: jan 1, 1970). The way I would approach the problem is take the date that the user entered, and create a java.util.Date() object from it. From that Date object, you can simply add/subtract the number of milliseconds from the user's "period".
Then, it simply becomes an exercise to print out the new date object.
Of course, I don't know if this is already too complicated for your class or not, but it is a fairly simple approach (assuming that you have already used Date objects) without using any 3rd party libs (like Joda Time).
As #Jon Skeet mentioned, use Joda Time. It will help you do the complex date calculations easily.

Categories