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.
Related
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.
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.
I am new to java and I am trying to figure out how to get the user input of time validated. If the user inputs a number lower then 800 or a number higher then 1900 the they should get the proper error message. I also want the user to get an error message if they input a time like 860 etc... I've been wrapped around this part for too long and I definitely need help.
import java.util.Scanner;
public class FugonIsaac06 {
public static void main(String[] args) {
boolean keepAsking = true;
Scanner reader = new Scanner(System.in);
String userInput = "";
int input_Start = 0;
int input_End = 0;
while (keepAsking) {
System.out.print("Please enter your name: ");
userInput = reader.nextLine();
if (userInput.length() >= 3) {
keepAsking = false;
} else {
System.out.println("Name must be at least 3 characters long.");
}
}
keepAsking = true;
//You will need to somehow separate the hours and minutes from the input.
//Use integer division and modulus to separate hours and minutes.
//Hours = Input / 100
//Minutes = Input % 100
//To convert the minutes to parts of an hour divide the minutes by 60.0.
//Parts of an hour = Minutes / 60.0
int hours_Start = input_Start / 100;
int minutes_Start = input_Start % 100;
while (keepAsking) {
System.out.print("Enter start time: ");
input_Start = reader.nextInt();
if ((input_Start > hours_Start) &&
(input_Start < minutes_Start)) {
keepAsking = true;
System.out.println("Start time should be between 800 and 1900");
} else {
System.out.println("Time is malformed, minutes should be between 0 and 59");
}
}
}
}
I would refactor your code to something like this:
Scanner reader = new Scanner(System.in);
String username = "";
do {
username = reader.nextLine();
} while(username.length() < 3);
int timeStart;
String timestamp = "";
// enter a timestamp in the form of hoursminutes
// hours = 0 (or 00) to 23
// minutes = 0 (or 00) to 59
do {
timestamp = reader.nextLine();
} while(!timestamp.matches("(?:2[0-3]|[0-1][0-9])[0-5][0-9]"));
// parse out the hours and minutes components
int hours = Integer.parseInt(timeStart) / 100;
int minutes = Integer.parseInt(timeStart) % 100;
Using do loops works well for your use case, because you want to eagerly accept an initial user input, regardless of any previous state, yet you want to have the ability to loop back again should validation fail. The while conditions validate the input, checking that a username have 3 or more characters, and that the time start is within the range you specified.
I have edited your code try it
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
boolean keepAsking = true;
Scanner reader = new Scanner(System.in);
String userInput = "";
int input_hours =0;
int input_End = 0;
String time;
while (keepAsking) {
System.out.print("Please enter your name: ");
userInput = reader.nextLine();
if (userInput.length() >= 3) {
break;
// keepAsking = false;
} else {
System.out.println("Name must be at least 3 characters long.");
}
}
keepAsking = true;
//You will need to somehow separate the hours and minutes from the input.
//Use integer division and modulus to separate hours and minutes.
//Hours = Input / 100
//Minutes = Input % 100
//To convert the minutes to parts of an hour divide the minutes by 60.0.
//Parts of an hour = Minutes / 60.0
int hours_Start = 0;
int minutes_Start = 0;
while (keepAsking) {
System.out.print("Enter start time HH:MM : ");
time = reader.next();
String []timeArr = time.split(":");
input_hours = Integer.parseInt(timeArr[0]);
minutes_Start = Integer.parseInt(timeArr[1]);
if (input_hours > 19 || input_hours < 8) {
keepAsking = true;
System.out.println("Start time should be between 800 and 1900");
} else if(minutes_Start<0 || minutes_Start>59){
System.out.println("Time is malformed, minutes should be between 0 and 59");
}else{
System.out.println("You have entered correct time");
break;
}
}
}
}
Can anyone help me here?? I have compiled and successfully run a program using Java which takes user inputs from an "inputdialog" box and displays this information back in the console along with a simple mathematical formula. The problem I cannot seem to overcome is when the data is input the user has an option to enter another set of the same data type but I need the console to register this as a second input. This is how far I am currently with the section of code and my ideas on how to make this work using an array but I have been informed that saving/storing the data as an object might be a better option?
private void enterCar()
{
String carInfo;
int carHours;
int i = 0;
int[] carNumb = new int[20];
double fee = Double.parseDouble("7.50");
double sum = 0;
final int MAX = 12;
{
carInfo = JOptionPane.showInputDialog("Please enter the license plate of the car");
carHours = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of hours the car was parked (1-12):"));
System.out.printf("\n");
System.out.printf("Details for car "+carNumb+" entered:\n");
System.out.printf("License plate Hours Fee:\n");
System.out.printf(""+carInfo+" "+carHours+" $");
if (carHours == 1)
System.out.printf("%3.2f",fee*(carHours));
else if (carNum == 2)
System.out.printf("%3.2f",fee+4.50);
else if (carHours >= 3)
System.out.printf("%3.2f",3+(carHours*4.50));
System.out.printf("\n\n");
}
}
When I compile and run the console I get the line "Details for car [I#6659c656 entered". This line does change to something like "[I#7665c575" the next time I activate the option so I can assume that I may need to assign a value to the number differently?
I have tried the option that is show in the code provided as well as trying to activate a list using (1, 2, 3, ect) but this also just outputs that random line of numbers and letters.
I guess to simplify my question. I need to store 20 individual inputs from an 'InputDialog' box and store it for later access in a console.
I need to store 20 individual inputs from an InputDialog box and store it for later access in a console.
Use a loop such as for.
That information then gets stored as "Details for car 1 entered:" and then the information displayed.
As I said before, you should use index of array instead of array. And because array is zero-based index, so I use carNumb[i] + 1 to print out the order.
Then calculate fee and store to carNumb array.
Note that, your fee is double type => carNumb should be double type to store correct value.
Full code:
public void enterCar() {
String carInfo;
int carHours;
int i = 0;
double[] carNumb = new double[20];
double fee = Double.parseDouble("7.50");
double sum = 0;
final int MAX = 12;
for (; i < carNumb.length; i++) {
carInfo = JOptionPane.showInputDialog("Please enter the license plate of the car");
carHours = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of hours the car was parked (1-12):"));
System.out.printf("\n");
System.out.printf("Details for car " + (carNumb[i] + 1) + " entered:\n");
System.out.printf("License plate Hours Fee:\n");
System.out.printf("" + carInfo + " " + carHours + " $");
carNumb[i] = getFee(fee, carHours);
System.out.printf("%3.2f", carNumb[i]);
System.out.printf("\n\n");
}
}
private double getFee(double fee, int hours) {
if (hours == 1) {
return fee;
}
if (hours == 2) {
return fee + 4.5;
}
if (hours >= 3) {
return 3 + hours * 4.5;
}
return 0;
}
Did I get your idea?
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.