SlideShare a Scribd company logo
1 of 12
Download to read offline
JAVA.
Q4: Create a Time class. This class will represent a point in time, such as a departure time. It
should contain 2 constructors, 2 instance variables (hour and minute), and 10 methods (see
below). All methods but toString should be in terms of the 24 hour format. [30 points]
default constructor: Creates a Time object for 12:00AM.
overloaded constructor: Creates a Time object at a specific hour and minute.
getHour(): Returns an integer representing the hour of the Time object.
getMinute(): Returns an integer representing the minute of the Time object.
addHours(...): Updates the object by moving it forward a number of hours.
addMinute(...): Updates the object by moving it forward a number of minutes. (Hint: Be careful
that you don't allow minutes to be more than 59.)
addTime(...): Updates the object by moving it forward by the hour and minute from another
Time object.
getCopy(...): Returns a new Time object that has the same hour and minute of the existing Time
object.
isEarlierThan(...): Returns true if this Time object is earlier than another Time object.
isSameTime(...): Returns true if this Time object is the same as another Time object.
isLaterThan(...): Returns true if this Time object is later than another Time object.
toString(): Returns a string representing the Time object. Uses 12 hour AM/PM format and pads
minutes to be two digits. See the sample output for an example.
Q5: Create a Flight class that uses the Plane and Time class. This class will represent a flight
between two airports, using a specific Plane, and departing at a specific Time. It should contain a
constructor, 7 instance variables (plane, flight number, cost, departure, duration, source,
destination), and 9 methods (see below). [25 points]
overloaded constructor: Creates a Flight object that is setup up with a Plane, a flight number, a
cost, a departure Time, a duration time, a source Airport, and a destination Airport.
getPlane(): Returns the Plane that operates this flight.
getNumber(): Returns the flight number.
getCost(): Returns the flight cost.
getDestination(): Returns the destination Airport.
getDeparture(): Returns the departure Time.
getArrival(): Returns a Time object with the arrival time (computed from the departure time and
duration).
getSource(): Returns a Airport object for the departure location.
toOverviewString(): Returns a String representing an overview of the flight. Use NumberFormat
to display the price. See the sample output for an example.
toDetailedString(): Returns a String representing the flight's detail information. See the sample
output for an example.
Included below is an overall UML diagram that describes the three classes you will be
constructing. It provides a useful summary of all of the methods you are expected to implement,
and their corresponding types and visibility. Notice that one private method is listed here
(formatDigits in Time) that isn't mentioned above. This is a method that was in our solution, you
may not need it in your answer. Conversely, you may implement additional private methods that
you find useful.
Solution
a.
public class Time{
private int hour;
private int minute;
private int second;
public Time(){
this(System.currentTimeMillis());
}
public Time(long elapseTime){
long totalSeconds = elapseTime / 1000L;
this.second = (int)(totalSeconds % 60L);
long totalMinutes = totalSeconds / 60L;
this.minute = (int)(totalMinutes % 60L);
int totalHours = (int)(totalMinutes / 60L);
this.hour = (totalHours % 24);
}
public String toString() {
return this.hour + ":" + this.minute + ":" + this.second + " GMT";
}
public int getHour() {
return this.hour;
}
public int getMinute() {
return this.minute;
}
public int getSecond() {
return this.second;
}
}
import java.io.IOException;
public class Time
{
private int hour;
private int minute;
public Time()
{
hour = 12;
minute = 0;
}
public Time(int h, int m)
{
if ( h >= 1 && h <= 23)
h = hour;
else
hour = 0;
if ( m >= 0 && m <= 59)
m = minute;
else
minute = 0;
}
public String toString()
{
String s = "";
if ( hour < 10 && minute < 10)
s = "0" + hour + "0" + minute;
else if ( hour < 10 && minute > 10)
s = "0" + hour + minute;
else if ( hour > 10 && minute < 10)
s = hour + "0" + minute;
else if ( hour == 0)
s = "0" + hour + minute;
else if ( minute == 0)
s = hour + "0" + minute;
return s;
}
public String convert()
{
String c = "";
if ( hour > 12)
c = "0" + (24 - hour) + minute + "pm";
else
c = hour + minute + "am";
return c;
}
public void increment()
{
minute++;
if (minute == 60)
{
hour++;
minute = 0;
}
else if ( hour == 24)
hour = 0;
}
public static void main(String str[]) throws IOException
{
Time time1 = new Time(14, 56);
System.out.println("time1: " + time1);
System.out.println("convert time1 to standard time: " + time1.convert());
System.out.println("time1: " + time1);
System.out.print("increment time1 five times: ");
time1.increment();
time1.increment();
time1.increment();
time1.increment();
time1.increment();
System.out.println(time1 + " ");
Time time2 = new Time(-7, 12);
System.out.println("time2: " + time2);
System.out.print("increment time2 67 times: ");
for (int i = 0; i < 67; i++)
time2.increment();
System.out.println(time2);
System.out.println("convert to time2 standard time: " + time2.convert());
System.out.println("time2: " + time2 + " ");
Time time3 = new Time(5, 17);
System.out.println("time3: " + time3);
System.out.print("convert time3: ");
System.out.println(time3.convert());
Time time4 = new Time(12, 15);
System.out.println(" time4: " + time4);
System.out.println("convert time4: " + time4.convert());
Time time5 = new Time(0, 15);
System.out.println(" time5: " + time5);
System.out.println("convert time5: " + time5.convert());
Time time6 = new Time(24, 15);
System.out.println(" time6: " + time6);
System.out.println("convert time6: " + time6.convert());
Time time7 = new Time(23,59);
System.out.println(" time7: " + time7);
System.out.println("convert time7: " + time7.convert());
time7.increment();
System.out.println("increment time7: " + time7);
System.out.println("convert time7: " + time7.convert());
}
}
import java.util.StringTokenizer;
import java.text.DecimalFormat;
public class Time
{
// instance data members - values for each different time object
private int hours;
private int minutes;
private boolean morning;
// constructors -----------------------------------------------
/** Default constructor
*/
public Time() { // default constructor, time is midnight
hours = 12;
minutes = 0;
morning = true;
}
/** Standard time constructor
@param h the hours
@param m the minutes
@param ap morning or afternoon indicator
*/
public Time(int h, int m, char ap) {
setHours(h);
setMinutes(m);
setWhen(ap);
}
/** Military time constructor
@param t the military time
*/
public Time(int t) { // t is military time
int h = t / 100;
setMinutes(t % 100);
if (h == 0) {
hours = 12;
morning = true;
} else if (h > 12) {
setHours(h - 12);
morning = false;
} else if (h < 12) {
setHours(h);
morning = true;
} else { // h == 12 == noon
hours = 12;
morning = false;
}
}
/** String constructor: "10:30 am" "2:15p" "06:01AM"
@param s the full standard time
*/
public Time(String s) {
s = s.toLowerCase();
int index = s.indexOf('a');
morning = true;
if (index < 0) {
index = s.indexOf('p');
morning = false;
}
if (index < 0) { // error - no a or p
index = s.length();
}
s = s.substring(0,index);
StringTokenizer tok = new StringTokenizer(s, ": ");
setHours(Integer.parseInt(tok.nextToken()));
setMinutes(Integer.parseInt(tok.nextToken()));
}
// instance methods --------------------------------------------
/** Set the hours, validity check
@param h the hours value
@return true if valid, false otherwise
*/
private boolean setHours(int h) {
if ( h > 0 && h <= 12) {
hours = h;
return true;
}
System.out.println("ERROR: invalid hours " + h);
hours = 12;
return false;
}
/** Set the minutes, validity check
@param m the minutes value
@return true if valid, false otherwise
*/
private boolean setMinutes(int m) {
if (m >= 0 && m < 60) {
minutes = m;
return true;
}
System.out.println("ERROR: invalid minutes " + m);
minutes = 0;
return false;
}
/** Set the morning indicator
@param ap the character a or p
*/
private void setWhen(char ap) {
ap = Character.toLowerCase(ap);
if (ap == 'a')
morning = true;
// check for invalid data later
else
morning = false;
}
/** Calculate current time plus more hours
@param h the hours to add
@return the new time result
*/
public Time addHours(int h) {
// get military
// add hours
// check if next day
// convert back
int mil = military();
int result = (mil / 100 + h) % 24; // new hours value
result = result * 100 + minutes;
return new Time(result);
}
/** Add minutes to the time
Pre-condition: 0 < m < 60
@param m the number of minutes to add
*/
public void addMinutes(int m) {
if (m >= 60 && m > 0) {
System.out.println("Error: can't add more than 59 minutes");
return;
}
minutes = minutes + m;
if (minutes > 59) {
minutes = minutes - 60;
hours++;
if (hours == 12) {
if (morning)
morning = false;
else
morning = true;
// morning = !morning;
}
if (hours > 12)
hours = hours - 12;
}
}
/** Display the time on standard output
*/
public void display() {
System.out.print(toString());
}
// gets called implicitly when needed to add object to a string
/** Create a string representation of the object
@return the string
*/
public String toString() {
// change to using Decimal Format
DecimalFormat two0 = new DecimalFormat("00");
String s = two0.format(hours) + ":" + two0.format(minutes);
s += (morning ? " am" : " pm");
return s;
}
/** Calculate the elapsed time in minutes between two times
2:15pm until 10:30pm = 8*60 + 15
10:30pm until 2:15pm = 15*60 + 45
@param t the end time
@return the elapsed time in minutes
*/
public int elapsed(Time t) {
int t1 = military(); // for implicit parameter
t1 = t1 / 100 * 60 + minutes; // elapsed mins since midnight
int t2 = t.military();
t2 = t2 / 100 * 60 + t.minutes;
int diff = t2 - t1;
if (diff < 0)
diff = diff + 24*60;
return diff;
}
/** Compare two times
@param the time to compare to
@return 0 if equal, - if implicit < explicit,
positive if implicit > explicit
*/
public int compareTo(Time t) {
return military() - t.military();
}
/** Check if the time is in the afternoon
@return true if it is, false otherwise
*/
public boolean isAfternoon() {
return !morning;
}
/** Convert the time to military format
@return the military time
*/
public int military() {
int mil;
if (morning) {
if (hours != 12)
mil = hours * 100;
else
mil = 0;
} else {
if (hours != 12)
mil = (hours+12) * 100;
else
mil = hours * 100;
}
return mil + minutes;
}
/** Convert the time to military format
@return the military time
*/
public String militaryString() {
DecimalFormat four0 = new DecimalFormat("0000");
return four0.format(military());
}
}
q5

More Related Content

Similar to JAVA.Q4 Create a Time class. This class will represent a point in.pdf

package employeeType.employee;public class Employee {    private.pdf
package employeeType.employee;public class Employee {    private.pdfpackage employeeType.employee;public class Employee {    private.pdf
package employeeType.employee;public class Employee {    private.pdfsharnapiyush773
 
Creating a Facebook Clone - Part XI.pdf
Creating a Facebook Clone - Part XI.pdfCreating a Facebook Clone - Part XI.pdf
Creating a Facebook Clone - Part XI.pdfShaiAlmog1
 
Write a java program to randomly generate the following sets of data.pdf
Write a java program to randomly generate the following sets of data.pdfWrite a java program to randomly generate the following sets of data.pdf
Write a java program to randomly generate the following sets of data.pdfarshin9
 
Advanced Java - Practical File
Advanced Java - Practical FileAdvanced Java - Practical File
Advanced Java - Practical FileFahad Shaikh
 
QA Fest 2019. Saar Rachamim. Developing Tools, While Testing
QA Fest 2019. Saar Rachamim. Developing Tools, While TestingQA Fest 2019. Saar Rachamim. Developing Tools, While Testing
QA Fest 2019. Saar Rachamim. Developing Tools, While TestingQAFest
 
Java programs
Java programsJava programs
Java programsjojeph
 
import java.util.LinkedList;import java.util.Scanner;public cla.pdf
import java.util.LinkedList;import java.util.Scanner;public cla.pdfimport java.util.LinkedList;import java.util.Scanner;public cla.pdf
import java.util.LinkedList;import java.util.Scanner;public cla.pdffakhrifoam
 
C++ code only(Retrieve of Malik D., 2015, p. 742) Programming Exer.pdf
C++ code only(Retrieve of Malik D., 2015, p. 742) Programming Exer.pdfC++ code only(Retrieve of Malik D., 2015, p. 742) Programming Exer.pdf
C++ code only(Retrieve of Malik D., 2015, p. 742) Programming Exer.pdfandreaplotner1
 
Write a program that obtains the execution time of selection sort, bu.pdf
Write a program that obtains the execution time of selection sort, bu.pdfWrite a program that obtains the execution time of selection sort, bu.pdf
Write a program that obtains the execution time of selection sort, bu.pdfarri2009av
 
Deep dumpster diving 2010
Deep dumpster diving 2010Deep dumpster diving 2010
Deep dumpster diving 2010RonnBlack
 
C++ Help, I cant find whats wrong in my program. The sample outp.pdf
C++ Help, I cant find whats wrong in my program. The sample outp.pdfC++ Help, I cant find whats wrong in my program. The sample outp.pdf
C++ Help, I cant find whats wrong in my program. The sample outp.pdfinfo998421
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 
OOP program questions with answers
OOP program questions with answersOOP program questions with answers
OOP program questions with answersQuratulain Naqvi
 
In this assignment you will practice creating classes and enumeratio.pdf
In this assignment you will practice creating classes and enumeratio.pdfIn this assignment you will practice creating classes and enumeratio.pdf
In this assignment you will practice creating classes and enumeratio.pdfivylinvaydak64229
 

Similar to JAVA.Q4 Create a Time class. This class will represent a point in.pdf (20)

Functional C++
Functional C++Functional C++
Functional C++
 
package employeeType.employee;public class Employee {    private.pdf
package employeeType.employee;public class Employee {    private.pdfpackage employeeType.employee;public class Employee {    private.pdf
package employeeType.employee;public class Employee {    private.pdf
 
Creating a Facebook Clone - Part XI.pdf
Creating a Facebook Clone - Part XI.pdfCreating a Facebook Clone - Part XI.pdf
Creating a Facebook Clone - Part XI.pdf
 
Write a java program to randomly generate the following sets of data.pdf
Write a java program to randomly generate the following sets of data.pdfWrite a java program to randomly generate the following sets of data.pdf
Write a java program to randomly generate the following sets of data.pdf
 
Advanced Java - Practical File
Advanced Java - Practical FileAdvanced Java - Practical File
Advanced Java - Practical File
 
QA Fest 2019. Saar Rachamim. Developing Tools, While Testing
QA Fest 2019. Saar Rachamim. Developing Tools, While TestingQA Fest 2019. Saar Rachamim. Developing Tools, While Testing
QA Fest 2019. Saar Rachamim. Developing Tools, While Testing
 
Thread
ThreadThread
Thread
 
Oop assignment 02
Oop assignment 02Oop assignment 02
Oop assignment 02
 
Java programs
Java programsJava programs
Java programs
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
 
Object - Based Programming
Object - Based ProgrammingObject - Based Programming
Object - Based Programming
 
import java.util.LinkedList;import java.util.Scanner;public cla.pdf
import java.util.LinkedList;import java.util.Scanner;public cla.pdfimport java.util.LinkedList;import java.util.Scanner;public cla.pdf
import java.util.LinkedList;import java.util.Scanner;public cla.pdf
 
C++ code only(Retrieve of Malik D., 2015, p. 742) Programming Exer.pdf
C++ code only(Retrieve of Malik D., 2015, p. 742) Programming Exer.pdfC++ code only(Retrieve of Malik D., 2015, p. 742) Programming Exer.pdf
C++ code only(Retrieve of Malik D., 2015, p. 742) Programming Exer.pdf
 
Write a program that obtains the execution time of selection sort, bu.pdf
Write a program that obtains the execution time of selection sort, bu.pdfWrite a program that obtains the execution time of selection sort, bu.pdf
Write a program that obtains the execution time of selection sort, bu.pdf
 
Deep dumpster diving 2010
Deep dumpster diving 2010Deep dumpster diving 2010
Deep dumpster diving 2010
 
C++ Help, I cant find whats wrong in my program. The sample outp.pdf
C++ Help, I cant find whats wrong in my program. The sample outp.pdfC++ Help, I cant find whats wrong in my program. The sample outp.pdf
C++ Help, I cant find whats wrong in my program. The sample outp.pdf
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
OOP program questions with answers
OOP program questions with answersOOP program questions with answers
OOP program questions with answers
 
In this assignment you will practice creating classes and enumeratio.pdf
In this assignment you will practice creating classes and enumeratio.pdfIn this assignment you will practice creating classes and enumeratio.pdf
In this assignment you will practice creating classes and enumeratio.pdf
 

More from karymadelaneyrenne19

Part A - Lymph Node Structure and FunctionUsing no more than 14 pr.pdf
Part A - Lymph Node Structure and FunctionUsing no more than 14 pr.pdfPart A - Lymph Node Structure and FunctionUsing no more than 14 pr.pdf
Part A - Lymph Node Structure and FunctionUsing no more than 14 pr.pdfkarymadelaneyrenne19
 
Is this a binomial probability experiment Please give a reason for .pdf
Is this a binomial probability experiment Please give a reason for .pdfIs this a binomial probability experiment Please give a reason for .pdf
Is this a binomial probability experiment Please give a reason for .pdfkarymadelaneyrenne19
 
in the case of the Bacillis strain, why would a young culture be use.pdf
in the case of the Bacillis strain, why would a young culture be use.pdfin the case of the Bacillis strain, why would a young culture be use.pdf
in the case of the Bacillis strain, why would a young culture be use.pdfkarymadelaneyrenne19
 
In HTTP response headers, what is the syntax of most lines (which ar.pdf
In HTTP response headers, what is the syntax of most lines (which ar.pdfIn HTTP response headers, what is the syntax of most lines (which ar.pdf
In HTTP response headers, what is the syntax of most lines (which ar.pdfkarymadelaneyrenne19
 
How is the mouth of planaria similar to the proboscis of Nemertean.pdf
How is the mouth of planaria similar to the proboscis of Nemertean.pdfHow is the mouth of planaria similar to the proboscis of Nemertean.pdf
How is the mouth of planaria similar to the proboscis of Nemertean.pdfkarymadelaneyrenne19
 
How do you define a species for asexually reproducing organisms; orga.pdf
How do you define a species for asexually reproducing organisms; orga.pdfHow do you define a species for asexually reproducing organisms; orga.pdf
How do you define a species for asexually reproducing organisms; orga.pdfkarymadelaneyrenne19
 
How do cognitive changes contribute to decision-making during adoles.pdf
How do cognitive changes contribute to decision-making during adoles.pdfHow do cognitive changes contribute to decision-making during adoles.pdf
How do cognitive changes contribute to decision-making during adoles.pdfkarymadelaneyrenne19
 
Describe the various types of computer-based information systems in .pdf
Describe the various types of computer-based information systems in .pdfDescribe the various types of computer-based information systems in .pdf
Describe the various types of computer-based information systems in .pdfkarymadelaneyrenne19
 
Day care centers expose children to a wider variety of germs than th.pdf
Day care centers expose children to a wider variety of germs than th.pdfDay care centers expose children to a wider variety of germs than th.pdf
Day care centers expose children to a wider variety of germs than th.pdfkarymadelaneyrenne19
 
Consider a two-state paramagnet with a very large number N of elemen.pdf
Consider a two-state paramagnet with a very large number N of elemen.pdfConsider a two-state paramagnet with a very large number N of elemen.pdf
Consider a two-state paramagnet with a very large number N of elemen.pdfkarymadelaneyrenne19
 
An administrator wishes to force remote access users to connect usin.pdf
An administrator wishes to force remote access users to connect usin.pdfAn administrator wishes to force remote access users to connect usin.pdf
An administrator wishes to force remote access users to connect usin.pdfkarymadelaneyrenne19
 
Below is a quote from Bobby Kennedy on what the Gross National Produ.pdf
Below is a quote from Bobby Kennedy on what the Gross National Produ.pdfBelow is a quote from Bobby Kennedy on what the Gross National Produ.pdf
Below is a quote from Bobby Kennedy on what the Gross National Produ.pdfkarymadelaneyrenne19
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfkarymadelaneyrenne19
 
Across the field of human development, “development” is defined as .pdf
Across the field of human development, “development” is defined as .pdfAcross the field of human development, “development” is defined as .pdf
Across the field of human development, “development” is defined as .pdfkarymadelaneyrenne19
 
A linked list is a linear data structure consisting of a set of nodes.pdf
A linked list is a linear data structure consisting of a set of nodes.pdfA linked list is a linear data structure consisting of a set of nodes.pdf
A linked list is a linear data structure consisting of a set of nodes.pdfkarymadelaneyrenne19
 
12. The white “Spirit” black bear, Ursys anerucabys kermodei, differ.pdf
12. The white “Spirit” black bear, Ursys anerucabys kermodei, differ.pdf12. The white “Spirit” black bear, Ursys anerucabys kermodei, differ.pdf
12. The white “Spirit” black bear, Ursys anerucabys kermodei, differ.pdfkarymadelaneyrenne19
 
With respect to the study of lawWhat is the purpose of discovery.pdf
With respect to the study of lawWhat is the purpose of discovery.pdfWith respect to the study of lawWhat is the purpose of discovery.pdf
With respect to the study of lawWhat is the purpose of discovery.pdfkarymadelaneyrenne19
 
Why do you need proteins to allow ions to cross the cell membrane an.pdf
Why do you need proteins to allow ions to cross the cell membrane an.pdfWhy do you need proteins to allow ions to cross the cell membrane an.pdf
Why do you need proteins to allow ions to cross the cell membrane an.pdfkarymadelaneyrenne19
 
When you digest a sample of your protein with Chymotrypsin you get a.pdf
When you digest a sample of your protein with Chymotrypsin you get a.pdfWhen you digest a sample of your protein with Chymotrypsin you get a.pdf
When you digest a sample of your protein with Chymotrypsin you get a.pdfkarymadelaneyrenne19
 
What type of rock can be dated with radiometric methodsSolution.pdf
What type of rock can be dated with radiometric methodsSolution.pdfWhat type of rock can be dated with radiometric methodsSolution.pdf
What type of rock can be dated with radiometric methodsSolution.pdfkarymadelaneyrenne19
 

More from karymadelaneyrenne19 (20)

Part A - Lymph Node Structure and FunctionUsing no more than 14 pr.pdf
Part A - Lymph Node Structure and FunctionUsing no more than 14 pr.pdfPart A - Lymph Node Structure and FunctionUsing no more than 14 pr.pdf
Part A - Lymph Node Structure and FunctionUsing no more than 14 pr.pdf
 
Is this a binomial probability experiment Please give a reason for .pdf
Is this a binomial probability experiment Please give a reason for .pdfIs this a binomial probability experiment Please give a reason for .pdf
Is this a binomial probability experiment Please give a reason for .pdf
 
in the case of the Bacillis strain, why would a young culture be use.pdf
in the case of the Bacillis strain, why would a young culture be use.pdfin the case of the Bacillis strain, why would a young culture be use.pdf
in the case of the Bacillis strain, why would a young culture be use.pdf
 
In HTTP response headers, what is the syntax of most lines (which ar.pdf
In HTTP response headers, what is the syntax of most lines (which ar.pdfIn HTTP response headers, what is the syntax of most lines (which ar.pdf
In HTTP response headers, what is the syntax of most lines (which ar.pdf
 
How is the mouth of planaria similar to the proboscis of Nemertean.pdf
How is the mouth of planaria similar to the proboscis of Nemertean.pdfHow is the mouth of planaria similar to the proboscis of Nemertean.pdf
How is the mouth of planaria similar to the proboscis of Nemertean.pdf
 
How do you define a species for asexually reproducing organisms; orga.pdf
How do you define a species for asexually reproducing organisms; orga.pdfHow do you define a species for asexually reproducing organisms; orga.pdf
How do you define a species for asexually reproducing organisms; orga.pdf
 
How do cognitive changes contribute to decision-making during adoles.pdf
How do cognitive changes contribute to decision-making during adoles.pdfHow do cognitive changes contribute to decision-making during adoles.pdf
How do cognitive changes contribute to decision-making during adoles.pdf
 
Describe the various types of computer-based information systems in .pdf
Describe the various types of computer-based information systems in .pdfDescribe the various types of computer-based information systems in .pdf
Describe the various types of computer-based information systems in .pdf
 
Day care centers expose children to a wider variety of germs than th.pdf
Day care centers expose children to a wider variety of germs than th.pdfDay care centers expose children to a wider variety of germs than th.pdf
Day care centers expose children to a wider variety of germs than th.pdf
 
Consider a two-state paramagnet with a very large number N of elemen.pdf
Consider a two-state paramagnet with a very large number N of elemen.pdfConsider a two-state paramagnet with a very large number N of elemen.pdf
Consider a two-state paramagnet with a very large number N of elemen.pdf
 
An administrator wishes to force remote access users to connect usin.pdf
An administrator wishes to force remote access users to connect usin.pdfAn administrator wishes to force remote access users to connect usin.pdf
An administrator wishes to force remote access users to connect usin.pdf
 
Below is a quote from Bobby Kennedy on what the Gross National Produ.pdf
Below is a quote from Bobby Kennedy on what the Gross National Produ.pdfBelow is a quote from Bobby Kennedy on what the Gross National Produ.pdf
Below is a quote from Bobby Kennedy on what the Gross National Produ.pdf
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
 
Across the field of human development, “development” is defined as .pdf
Across the field of human development, “development” is defined as .pdfAcross the field of human development, “development” is defined as .pdf
Across the field of human development, “development” is defined as .pdf
 
A linked list is a linear data structure consisting of a set of nodes.pdf
A linked list is a linear data structure consisting of a set of nodes.pdfA linked list is a linear data structure consisting of a set of nodes.pdf
A linked list is a linear data structure consisting of a set of nodes.pdf
 
12. The white “Spirit” black bear, Ursys anerucabys kermodei, differ.pdf
12. The white “Spirit” black bear, Ursys anerucabys kermodei, differ.pdf12. The white “Spirit” black bear, Ursys anerucabys kermodei, differ.pdf
12. The white “Spirit” black bear, Ursys anerucabys kermodei, differ.pdf
 
With respect to the study of lawWhat is the purpose of discovery.pdf
With respect to the study of lawWhat is the purpose of discovery.pdfWith respect to the study of lawWhat is the purpose of discovery.pdf
With respect to the study of lawWhat is the purpose of discovery.pdf
 
Why do you need proteins to allow ions to cross the cell membrane an.pdf
Why do you need proteins to allow ions to cross the cell membrane an.pdfWhy do you need proteins to allow ions to cross the cell membrane an.pdf
Why do you need proteins to allow ions to cross the cell membrane an.pdf
 
When you digest a sample of your protein with Chymotrypsin you get a.pdf
When you digest a sample of your protein with Chymotrypsin you get a.pdfWhen you digest a sample of your protein with Chymotrypsin you get a.pdf
When you digest a sample of your protein with Chymotrypsin you get a.pdf
 
What type of rock can be dated with radiometric methodsSolution.pdf
What type of rock can be dated with radiometric methodsSolution.pdfWhat type of rock can be dated with radiometric methodsSolution.pdf
What type of rock can be dated with radiometric methodsSolution.pdf
 

Recently uploaded

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 

Recently uploaded (20)

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 

JAVA.Q4 Create a Time class. This class will represent a point in.pdf

  • 1. JAVA. Q4: Create a Time class. This class will represent a point in time, such as a departure time. It should contain 2 constructors, 2 instance variables (hour and minute), and 10 methods (see below). All methods but toString should be in terms of the 24 hour format. [30 points] default constructor: Creates a Time object for 12:00AM. overloaded constructor: Creates a Time object at a specific hour and minute. getHour(): Returns an integer representing the hour of the Time object. getMinute(): Returns an integer representing the minute of the Time object. addHours(...): Updates the object by moving it forward a number of hours. addMinute(...): Updates the object by moving it forward a number of minutes. (Hint: Be careful that you don't allow minutes to be more than 59.) addTime(...): Updates the object by moving it forward by the hour and minute from another Time object. getCopy(...): Returns a new Time object that has the same hour and minute of the existing Time object. isEarlierThan(...): Returns true if this Time object is earlier than another Time object. isSameTime(...): Returns true if this Time object is the same as another Time object. isLaterThan(...): Returns true if this Time object is later than another Time object. toString(): Returns a string representing the Time object. Uses 12 hour AM/PM format and pads minutes to be two digits. See the sample output for an example. Q5: Create a Flight class that uses the Plane and Time class. This class will represent a flight between two airports, using a specific Plane, and departing at a specific Time. It should contain a constructor, 7 instance variables (plane, flight number, cost, departure, duration, source, destination), and 9 methods (see below). [25 points] overloaded constructor: Creates a Flight object that is setup up with a Plane, a flight number, a cost, a departure Time, a duration time, a source Airport, and a destination Airport. getPlane(): Returns the Plane that operates this flight. getNumber(): Returns the flight number. getCost(): Returns the flight cost. getDestination(): Returns the destination Airport. getDeparture(): Returns the departure Time. getArrival(): Returns a Time object with the arrival time (computed from the departure time and duration). getSource(): Returns a Airport object for the departure location. toOverviewString(): Returns a String representing an overview of the flight. Use NumberFormat
  • 2. to display the price. See the sample output for an example. toDetailedString(): Returns a String representing the flight's detail information. See the sample output for an example. Included below is an overall UML diagram that describes the three classes you will be constructing. It provides a useful summary of all of the methods you are expected to implement, and their corresponding types and visibility. Notice that one private method is listed here (formatDigits in Time) that isn't mentioned above. This is a method that was in our solution, you may not need it in your answer. Conversely, you may implement additional private methods that you find useful. Solution a. public class Time{ private int hour; private int minute; private int second; public Time(){ this(System.currentTimeMillis()); } public Time(long elapseTime){ long totalSeconds = elapseTime / 1000L; this.second = (int)(totalSeconds % 60L); long totalMinutes = totalSeconds / 60L; this.minute = (int)(totalMinutes % 60L); int totalHours = (int)(totalMinutes / 60L); this.hour = (totalHours % 24); } public String toString() { return this.hour + ":" + this.minute + ":" + this.second + " GMT"; } public int getHour() { return this.hour; } public int getMinute() { return this.minute;
  • 3. } public int getSecond() { return this.second; } } import java.io.IOException; public class Time { private int hour; private int minute; public Time() { hour = 12; minute = 0; } public Time(int h, int m) { if ( h >= 1 && h <= 23) h = hour; else hour = 0; if ( m >= 0 && m <= 59) m = minute; else minute = 0; } public String toString() { String s = ""; if ( hour < 10 && minute < 10) s = "0" + hour + "0" + minute; else if ( hour < 10 && minute > 10) s = "0" + hour + minute; else if ( hour > 10 && minute < 10) s = hour + "0" + minute;
  • 4. else if ( hour == 0) s = "0" + hour + minute; else if ( minute == 0) s = hour + "0" + minute; return s; } public String convert() { String c = ""; if ( hour > 12) c = "0" + (24 - hour) + minute + "pm"; else c = hour + minute + "am"; return c; } public void increment() { minute++; if (minute == 60) { hour++; minute = 0; } else if ( hour == 24) hour = 0; } public static void main(String str[]) throws IOException { Time time1 = new Time(14, 56); System.out.println("time1: " + time1); System.out.println("convert time1 to standard time: " + time1.convert()); System.out.println("time1: " + time1); System.out.print("increment time1 five times: "); time1.increment(); time1.increment(); time1.increment();
  • 5. time1.increment(); time1.increment(); System.out.println(time1 + " "); Time time2 = new Time(-7, 12); System.out.println("time2: " + time2); System.out.print("increment time2 67 times: "); for (int i = 0; i < 67; i++) time2.increment(); System.out.println(time2); System.out.println("convert to time2 standard time: " + time2.convert()); System.out.println("time2: " + time2 + " "); Time time3 = new Time(5, 17); System.out.println("time3: " + time3); System.out.print("convert time3: "); System.out.println(time3.convert()); Time time4 = new Time(12, 15); System.out.println(" time4: " + time4); System.out.println("convert time4: " + time4.convert()); Time time5 = new Time(0, 15); System.out.println(" time5: " + time5); System.out.println("convert time5: " + time5.convert()); Time time6 = new Time(24, 15); System.out.println(" time6: " + time6); System.out.println("convert time6: " + time6.convert()); Time time7 = new Time(23,59); System.out.println(" time7: " + time7); System.out.println("convert time7: " + time7.convert()); time7.increment(); System.out.println("increment time7: " + time7); System.out.println("convert time7: " + time7.convert()); } } import java.util.StringTokenizer; import java.text.DecimalFormat;
  • 6. public class Time { // instance data members - values for each different time object private int hours; private int minutes; private boolean morning; // constructors ----------------------------------------------- /** Default constructor */ public Time() { // default constructor, time is midnight hours = 12; minutes = 0; morning = true; } /** Standard time constructor @param h the hours @param m the minutes @param ap morning or afternoon indicator */ public Time(int h, int m, char ap) { setHours(h); setMinutes(m); setWhen(ap); } /** Military time constructor @param t the military time */ public Time(int t) { // t is military time int h = t / 100; setMinutes(t % 100); if (h == 0) { hours = 12; morning = true; } else if (h > 12) { setHours(h - 12);
  • 7. morning = false; } else if (h < 12) { setHours(h); morning = true; } else { // h == 12 == noon hours = 12; morning = false; } } /** String constructor: "10:30 am" "2:15p" "06:01AM" @param s the full standard time */ public Time(String s) { s = s.toLowerCase(); int index = s.indexOf('a'); morning = true; if (index < 0) { index = s.indexOf('p'); morning = false; } if (index < 0) { // error - no a or p index = s.length(); } s = s.substring(0,index); StringTokenizer tok = new StringTokenizer(s, ": "); setHours(Integer.parseInt(tok.nextToken())); setMinutes(Integer.parseInt(tok.nextToken())); } // instance methods -------------------------------------------- /** Set the hours, validity check @param h the hours value @return true if valid, false otherwise */ private boolean setHours(int h) {
  • 8. if ( h > 0 && h <= 12) { hours = h; return true; } System.out.println("ERROR: invalid hours " + h); hours = 12; return false; } /** Set the minutes, validity check @param m the minutes value @return true if valid, false otherwise */ private boolean setMinutes(int m) { if (m >= 0 && m < 60) { minutes = m; return true; } System.out.println("ERROR: invalid minutes " + m); minutes = 0; return false; } /** Set the morning indicator @param ap the character a or p */ private void setWhen(char ap) { ap = Character.toLowerCase(ap); if (ap == 'a') morning = true; // check for invalid data later else morning = false; } /** Calculate current time plus more hours @param h the hours to add @return the new time result */
  • 9. public Time addHours(int h) { // get military // add hours // check if next day // convert back int mil = military(); int result = (mil / 100 + h) % 24; // new hours value result = result * 100 + minutes; return new Time(result); } /** Add minutes to the time Pre-condition: 0 < m < 60 @param m the number of minutes to add */ public void addMinutes(int m) { if (m >= 60 && m > 0) { System.out.println("Error: can't add more than 59 minutes"); return; } minutes = minutes + m; if (minutes > 59) { minutes = minutes - 60; hours++; if (hours == 12) { if (morning) morning = false; else morning = true; // morning = !morning; } if (hours > 12) hours = hours - 12; } } /** Display the time on standard output */
  • 10. public void display() { System.out.print(toString()); } // gets called implicitly when needed to add object to a string /** Create a string representation of the object @return the string */ public String toString() { // change to using Decimal Format DecimalFormat two0 = new DecimalFormat("00"); String s = two0.format(hours) + ":" + two0.format(minutes); s += (morning ? " am" : " pm"); return s; } /** Calculate the elapsed time in minutes between two times 2:15pm until 10:30pm = 8*60 + 15 10:30pm until 2:15pm = 15*60 + 45 @param t the end time @return the elapsed time in minutes */ public int elapsed(Time t) { int t1 = military(); // for implicit parameter t1 = t1 / 100 * 60 + minutes; // elapsed mins since midnight int t2 = t.military(); t2 = t2 / 100 * 60 + t.minutes; int diff = t2 - t1; if (diff < 0) diff = diff + 24*60; return diff; } /** Compare two times @param the time to compare to @return 0 if equal, - if implicit < explicit,
  • 11. positive if implicit > explicit */ public int compareTo(Time t) { return military() - t.military(); } /** Check if the time is in the afternoon @return true if it is, false otherwise */ public boolean isAfternoon() { return !morning; } /** Convert the time to military format @return the military time */ public int military() { int mil; if (morning) { if (hours != 12) mil = hours * 100; else mil = 0; } else { if (hours != 12) mil = (hours+12) * 100; else mil = hours * 100; } return mil + minutes; } /** Convert the time to military format @return the military time */ public String militaryString() { DecimalFormat four0 = new DecimalFormat("0000"); return four0.format(military()); }
  • 12. } q5