I've got 2 classes: Deadline and Task. Within the Task class, I want to create an extendDeadline method where it increases the deadline of a task. I tried the following:
public void extendDeadline(int extend){
deadline = deadline + extend;
}
but this didn't work because the type of deadline is Deadline. Can anyone help me?
Code for deadline class:
import java.text.DateFormat;
import java.util.Date;
public class Deadline {
// dates are stored as the number of seconds since 01/01/1970
private long deadline;
// we have a DateFormat to format the date as text
private DateFormat dateFormatter;
// define some constants...
public static final long SECOND = 1000;
public static final long MINUTE = SECOND*60;
public static final long HOUR = MINUTE * 60;
public static final long DAY = HOUR*24;
public static final long WEEK = DAY*7;
/**
* Construct a new deadline.
* By default, deadlines are one week ahead of the time now.
*/
public Deadline() {
// by default you get a week
deadline = now() + WEEK;
dateFormatter = DateFormat.getDateInstance();
}
/**
* #return the time now as a long
*/
private long now() {
return new Date().getTime();
}
/**
* Get the date of this deadline as a Date object.
* #return the date of this deadline as a Date object.
*/
private Date getDeadlineDate() {
return new Date(deadline);
}
/**
* Change the date of this deadline by a specified number of days.
* #param numDays the number of days to add to the deadline date (may be negative).
*/
public void setNewDeadline(int numDays) {
deadline = deadline + (DAY*numDays);
}
/**
* Find out if this deadline has passed.
* #return true when the time now is later than the deadline.
*/
public boolean hasPassed() {
return now() > deadline;
}
/**
* Return this deadline formatted as text to be printed.
* #return a string representation of this deadline.
*/
#Override
public String toString() {
return dateFormatter.format(getDeadlineDate());
}
#Override
public boolean equals(Object o) {
if (o instanceof Deadline) {
Deadline other = (Deadline) o;
if (this.toString().equals(other.toString())) {
return true;
} else {
return false;
}
} else {
return false;
}
}
}
code for task class:
public class Task {
private int id;
private String description;
private Deadline deadline;
private boolean done;
private int estimatedLength;
private int hoursWork;
/**
* Constructor for objects of class Task
*/
public Task(int id , String description, int estimatedLength) {
this.description = description;
this.id = id;
this.estimatedLength = estimatedLength;
deadline = new Deadline();
done = false;
hoursWork = hoursWork;
}
public int getId(){
return id;
}
public Deadline getDeadline(){
return deadline;
}
public String getDescription(){
return description;
}
public boolean isDone(){
return done;
}
public double getPercentageComplete(){ //make sure this is right
double result = 0;
double hoursWorkDouble = (double) hoursWork;
double estimatedLengthDouble = (double) estimatedLength;
result = (double) hoursWork / (double) estimatedLength * 100.0;
System.out.println("Percentage complete: "+result);
return result;
}
public boolean isLate(){
if(done = false) { // dont forget to put AND date greater deadline
return true;
} else{
return false;
}
}
public void setDone(){
this.done = true;
}
public void extendEstimate(int extendEstimate){
estimatedLength = estimatedLength + extendEstimate;
/*int extendEstimate= 0;
int estimatedLength= 0;
int result= extendEstimate + estimatedLength;
System.out.println(+result);
*/
}
public void recordHoursWorked(int recordHours){
hoursWork= hoursWork + recordHours;
}
public void extendDeadline(int extend){
}
}
It looks like you have an setNewDeadline(int numDays) method in your Deadline class. (this should probably be renamed to something like extendDeadlineByDays because you're not resetting the deadline, just extending it) It looks like what you actually want to do is call that method. So, in the Task class, the method should look like this:
public void extendDeadline(int extend){
deadline.setNewDeadline(extend);
}
In this case you're updating the deadline, rather than trying to reassign it. What you were trying to do was take a Deadline, and add an int to it, which is impossible.
Related
Basically, I need to make the closeDate = null and the openDate the current date. Using latest version of Java SDK and netbeans.
import java.util.Date;
public class Task {
Date openDate = new Date();
Date closeDate = new Date();
public int taskType;
public Task(int taskType)
{
this.taskType = taskType;
}
static void setOpenDate(Date openDate)
{
}
static void setCloseDate(Date closeDate)
{
}
static void setTaskType(int taskType)
{
}
static int getTaskType()
{
}
static Date getOpenDate()
{
return openDate;
}
static Date getCloseDate()
{
return closeDate;
}
}
This is what I have. I'm losing my mind on other parts of this painful assignment, but I just need some form of clarity for something.
Remove "static" modifier from methods and create setter and getter instance level. You can use Java 8 LocalDate for date and time but I don't think you need it for you current purpose.
You can initialize instance variables as defined in below code snippet, Below code will initialize the open date as current date and close date as null once you create new object of Task
import java.util.Date;
public class Task {
private Date openDate = new Date();
private Date closeDate = null;
public int taskType;
public Task(int taskType) {
this.taskType = taskType;
}
public Date getOpenDate() {
return openDate;
}
public void setOpenDate(Date openDate) {
this.openDate = openDate;
}
public Date getCloseDate() {
return closeDate;
}
public void setCloseDate(Date closeDate) {
this.closeDate = closeDate;
}
public int getTaskType() {
return taskType;
}
public void setTaskType(int taskType) {
this.taskType = taskType;
}
}
Hi Please find sample program below to get Date with current time when you calling along with closing date as null,
public class UpdateDate {
LocalDateTime getCurrentDate(){
LocalDateTime openDate = LocalDateTime.now();
System.out.println("Current date: "+openDate);
return openDate;
}
Date getClosingDate(){
Date closingDate = null;
System.out.println("Closing date: "+closingDate);
return closingDate;
}
public static void main(String[] args) {
UpdateDate ud = new UpdateDate();
ud.getCurrentDate();
ud.getClosingDate();
}
}
it produce below output and you can change it to whatever the format you like using format and parsing methods from Date class in java.
output
Current date: 2018-08-22T18:55:35.906
Closing date: null
So I have to create a Bank Simulator project for class, and so far I have a few of the methods implemnted. But currently I am having trouble with the doBusiness method in the ServiceCenter class. Here is the code I have so far.
Main: BankSimulator
import java.util.Scanner;
public class BankSimulator {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("What is the time duration (in minutes) to be simulated? ");
int maxTime = input.nextInt();
System.out.print("What percentage of the time (0-100) does a customer arrive? ");
int arrivalProb = input.nextInt();
ServiceCenter bank = new ServiceCenter();
while (bank.getTime() <= maxTime || bank.customersRemaining()) {
if (bank.getTime() <= maxTime && customerArrived(arrivalProb)) {
bank.addCustomer();
}
bank.doBusiness();
}
//bank.displayStats();
}
private static boolean customerArrived(int prob)
{
return (Math.random()*100 <= prob);
}
}
Server class:
public class Server {
private static int nextID = 1;
private int serverID;
private int endTime;
private Customer serving;
public Server()
{
serverID = nextID;
nextID++;
endTime = 0;
serving = null;
}
/**
* Accessor method for getting the server ID number.
* #return the server ID
*/
public int getID()
{
return serverID;
}
/**
* Assigns a customer to the server and begins the transaction.
* #param c the new customer to be served
* #param time the time at which the transaction begins
*/
public void startCustomer(Customer c, int time)
{
serving = c;
endTime = time + c.getJobLength();
}
/**
* Accessor method for getting the current customer.
* #return the current customer, or null if no customer
*/
public Customer getCustomer()
{
return serving;
}
/**
* Identifies the time at which the server will finish with
* the current customer
* #return time at which transaction will finish, or 0 if no customer
*/
public int busyUntil()
{
return endTime;
}
/**
* Finishes with the current customer and resets the time to completion.
*/
public void finishCustomer()
{
serving = null;
endTime = 0;
}
}
Customer class:
import java.util.Random;
public class Customer {
private static final int MAX_LENGTH = 8;
private static final Random rand = new Random();
private static int nextID = 1;
private int customerID;
private int arrivalTime;
private int jobLength;
/**
* Constructs a customer with the next available ID number,
* the specified arrival time, and a random job length.
* #param arrTime the time at which the customer arrives
*/
public Customer(int arrTime)
{
customerID = nextID;
nextID++;
arrivalTime = arrTime;
jobLength = rand.nextInt(MAX_LENGTH)+1;
}
/**
* Accessor method for getting the customer's ID number.
* #return the customer ID
*/
public int getID()
{
return customerID;
}
/**
* Accessor method for getting the customer's arrival time.
* #return the time at which the customer arrived
*/
public int getArrivalTime()
{
return arrivalTime;
}
/**
* Accessor method for getting the length of the job
* #return the job length (in minutes)
*/
public int getJobLength()
{
return jobLength;
}
}
I had to create the following class called ServiceCenter where getTime returns the time in the simulation which starts at 0 and increments on each step. An addCustomer method where we add a customer to the queue and displayed a message. A customerRemaining which returns true if a customer is currently being waited on. Lastly the doBusiness method which increments the time, if the server finished with a customer remove them from the queue, and if the server is free and there is a customer in the queue, begin serving them. I have the first few ones done except the doBusiness method I am stuck on. Does anyone have any tips?
The code listed above was created by Dave Reed and I take no credit for the code.
ServiceCenter class:
import java.util.LinkedList;
import java.util.Queue;
public class ServiceCenter {
private int arrivalTime, departureTime;
private Queue <Customer> customer;
private Server server;
public ServiceCenter()
{
server = new Server();
customer = new LinkedList <Customer> ();
}
public String addCustomer ()
{
Customer customer1 = new Customer (arrivalTime);
customer.add(customer1);
String result = "" + customer1.getArrivalTime() + "" + customer1.getID() + "" + customer1.getJobLength();
return result;
}
public void doBusiness()
{
if(!customer.isEmpty())
{
if(server == null)
{
customer.remove();
}
}
}
public int getTime()
{
return departureTime - arrivalTime;
}
public boolean customersRemaining()
{
if (!(customer.isEmpty()))
return true;
else
return false;
}
}
Any help at all or tips would be greatly appreciated. I've been trying to figure it out for a week now, but for some reason queues are my weakness. Thanks for reading and sorry for it being so long. Just wanted it to be detailed.
You are using new Customer (arrivalTime); but you don't have the arrivalTime in your constructor of the ServiceCenter-class.
Main question:
Each flight has a number (this must start with letters EI and be followed by 3 digits), a day of the week the flight travels, a destination and the number of seats booked. Each flight will also have the standard responsibilities and the ability to calculate and return the number of free seats on a flight (assume each flight has a maximum of 10). You should use your imaginations to create one other flight responsibility that you think would be useful (this could also involve the creation of one or more new data items to support the responsibility).
This is what i have done so far:
public class Flight{
private String flightNo;
private date day;
private String
private int numberOfBookedSeats;
private int freeSeats=0;
private int passengerMeals;
private int mealsNeeded=0;
public Flight(){
}
public Flight(String flightNo, date day,String destination,int numberOfBookedSeats,int passengerMeals ){
this.flightNo= flightNo;
this.day = day;
this.destination= destination;
this.numeberOfSeats= numberOfSeats;
this.passengerMeals= passengerMeals;
}
public void setFlightNo(filghtNo f){
flightNo= f;
}
public String getFlightNo() {
return flightNo;
}
public void setDay(Day d) {
day= d;
}
public int getDay(){
return day;
}
public void setDestination(destination ds) {
destination = ds;
}
public int getDestination(){
return destination;
}
public void setNumeberOfSeats(numberOfSeats s){
numberOfSeats= s;
}
public int getNumeberOfSeats(){
return numeberOfSeats;
}
public void setPassengerMeals( passengerMeals pm){
passengerMeals= pm;
}
public int getPassengerMeals(){
return passengerMeals;
}
public int calculateFreeSeats(){
int maxSeatsNumbers = 10;
freeSeats = maxSeatsNumbers - numberOfBookedSeats;
return freeSeats;
}
public int calculateMealsNeeded(){
int staffMeals=5;
passengerMeals= numberOfBookedSeats;
mealsNeeded= staffMeals + passengerMeals;
return mealsNeeded;
}
}
Anint is not the correct class to store the flight number as, as it does not allow for the prefix characters or for the width to be specified. You could store it as a String, which would allow the prefix, and then do some validation and possibly padding to the numeric part, but what I would do is create a new type to represent the flight number.
This encapsulates the logic used to generate the flight number from the prefix String & int, making it more maintainable as the validation logic is just in one place, and it makes the code more understandable as your Flight class no longer has to contain logic to do with generating String flight numbers. It's a lot more clear in use, as well, because if you have a private final FlightNumber flightNumber member, you can use it in a String with something like "The flight number is " + flightNumber;.
See the following for what this type could look like:
Note this particular implementation uses Guava's Strings class - if you're not using this already it's probably not worth importing it just for this, so implement an equivalent yourself using String.format("%03d", ...) or similar, but if you've got Guava I think it looks cleaner.
import com.google.common.base.Strings;
public class FlightNumber {
private final String prefix;
private final int flightId;
public FlightNumber(String prefix, int flightId) {
if (flightId < 0 || flightId > 999) {
throw new IllegalArgumentException("Invalid Flight ID [" + flightId + "]");
}
this.prefix = prefix;
this.flightId = flightId;
}
#Override
public String toString() {
return prefix + Strings.padStart(String.valueOf(flightId), 3, '0');
}
}
If you wanted to extend this in the future, and your code suited this kind of design, you could then do something like the following:
public class AerLingusFlightNumber extends FlightNumber {
public AerLingusFlightNumber(int flightId) {
super("EI", flightId);
}
}
And:
public class BritishAirwaysFlightNumber extends FlightNumber {
public BritishAirwaysFlightNumber(int flightId) {
super("BA", flightId);
}
}
You should only create one public Constructor due to a Flight must have a FlightNumber (must be a String).
Also I would check at the body of the constructor the following:
if (!flightNumber.matchs("^EI\d{3}$")) {
throw new IllegalArgumentException("Invalid Flight number format.");
}
flightNo = flightNumber;
If you want your fight number to be alpha numeric then int is not the correct data type, you should use String and for validating that you could use the String method matches in conjunction with a regular expression.
Here is something you could start with:
class AirLine {
List<Flight> flights = new ArrayList<>();
public void addFlight(String flightNumber) {
flights.add(new Flight(flightNumber));
}
public List<Flight> getFlights() {
return flights;
}
}
class Flight {
String flightNumber;
public Flight(String flightNumber) {
setFlightNumber(flightNumber);
}
public String getFlightNumber() {
return flightNumber;
}
public void setFlightNumber(String flightNumber) {
if(flightNumber == null || ! flightNumber.matches("EI\\d{3}")) {
throw new IllegalArgumentException("invalid flight number: "
+ flightNumber);
}
this.flightNumber = flightNumber;
}
}
This question already has an answer here:
Design a class named Time in java
(1 answer)
Closed 9 years ago.
I've been working on this assignment for a while and I've hit a wall that I can't figure a way around. The goal of the assignment can be read here, to save me the trouble of typing or copying it.
http://imgur.com/be5YVst
I can't figure out the output portion of the assignment. Because the class had to be set up in such a specific way, and not just to perform a specific function. Even though the assignment says nothing about a toString() or similar method, I started to write one, but realized that I couldn't use the fields, hour, minute, and second because they're out of scope. If I tried to put them in the TimeTest program instead, I won't have permission because they're private. (They HAVE to be private.)
How can I get these converted units to be printed out in the form hour:minute:second?
Below is my current code:
public class Time
{
private long hour;
private long minute;
private long second;
public Time()
{
long compTime = System.currentTimeMillis();
this.setTime(compTime);
}
public Time(long hour, long minute, long second)
{
this.hour = hour;
this.minute = minute;
this.second = second;
}
public Time(long time)
{
this.setTime(time);
}
//three get methods
public long getHour()
{
return this.hour;
}
public long getMinute()
{
return this.minute;
}
public long getSecond()
{
return this.second;
}
//setTime method
public void setTime(long elapseTime)
{
this.hour = (elapseTime/36000000);
this.minute = ((elapseTime - (this.hour * 36000000))/60000);
this.second = ((elapseTime - (this.minute * 60000))/1000);
}
public String printFormat()
{
//it wouldn't let me name it toString() so I named it printFormat() instead.
}
}
try
#Override
public String toString() {
// create a string from your fields
}
Try this,
class Time
{
private long hour;
private long minute;
private long second;
public Time()
{
long compTime = System.currentTimeMillis();
this.setTime(compTime);
}
public Time(long hour, long minute, long second)
{
this.hour = hour;
this.minute = minute;
this.second = second;
}
public Time(long time)
{
this.setTime(time);
}
//three get methods
public long getHour()
{
return this.hour;
}
public long getMinute()
{
return this.minute;
}
public long getSecond()
{
return this.second;
}
//setTime method
public void setTime(long elapseTime)
{
this.hour = (elapseTime/36000000);
this.minute = ((elapseTime - (this.hour * 36000000))/60000);
this.second = ((elapseTime - (this.minute * 60000))/1000);
}
public String printFormat()
{
return hour + ":" + minute + ":" + second;
}
}
public class TimeTest
{
public static void main(String[] args)
{
System.out.println(new Time().printFormat());
}
}
I call this method in java:
private void updateDisplay()
{
displayString = hours.getDisplayValue() + ":" +
minutes.getDisplayValue();
}
What triggers this method two times for hours and minutes:
public String getDisplayValue()
{
if(value < 10) {
return "0" + value;
}
else {
return "" + value;
}
}
My question is how can i check in getDisplayValue if the method is triggerd as minute or as hour? For example:
public String getDisplayValue()
{ if(this == minutes){
if(value < 10) {
return "0" + value;
}
else {
return "" + value;
}
}
Entire code:
public class ClockDisplay
{
private NumberDisplay hours;
private NumberDisplay minutes;
private String displayString; // simulates the actual display
/**
* Constructor for ClockDisplay objects. This constructor
* creates a new clock set at 00:00.
*/
public ClockDisplay()
{
hours = new NumberDisplay(24);
minutes = new NumberDisplay(60);
updateDisplay();
}
/**
* Constructor for ClockDisplay objects. This constructor
* creates a new clock set at the time specified by the
* parameters.
*/
public ClockDisplay(int hour, int minute)
{
hours = new NumberDisplay(24);
minutes = new NumberDisplay(60);
setTime(hour, minute);
}
/**
* This method should get called once every minute - it makes
* the clock display go one minute forward.
*/
public void timeTick()
{
minutes.increment();
if(minutes.getValue() == 0) { // it just rolled over!
hours.increment();
}
updateDisplay();
}
/**
* Set the time of the display to the specified hour and
* minute.
*/
public void setTime(int hour, int minute)
{
hours.setValue(hour);
minutes.setValue(minute);
updateDisplay();
}
/**
* Return the current time of this display in the format HH:MM.
*/
public String getTime()
{
return displayString;
}
/**
* Update the internal string that represents the display.
*/
private void updateDisplay()
{
displayString = hours.getDisplayValue() + ":" +
minutes.getDisplayValue();
}
}
And:
public class NumberDisplay
{
private int limit;
private int value;
/**
* Constructor for objects of class NumberDisplay.
* Set the limit at which the display rolls over.
*/
public NumberDisplay(int rollOverLimit)
{
limit = rollOverLimit;
value = 0;
}
/**
* Return the current value.
*/
public int getValue()
{
return value;
}
/**
* Return the display value (that is, the current value as a two-digit
* String. If the value is less than ten, it will be padded with a leading
* zero).
*/
public String getDisplayValue()
{
if(value < 10) {
return "0" + value;
}
else {
return "" + value;
}
}
/**
* Set the value of the display to the new specified value. If the new
* value is less than zero or over the limit, do nothing.
*/
public void setValue(int replacementValue)
{
if((replacementValue >= 0) && (replacementValue < limit)) {
value = replacementValue;
}
}
/**
* Increment the display value by one, rolling over to zero if the
* limit is reached.
*/
public void increment()
{
value = (value + 1) % limit;
}
}
}
Do it using reflection by checking the stack trace, see Thread#getStackTrace:
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()
Go through the API and see what methods are useful for your needs.
But why don't you simply pass an identifier that allows you to detect who called the method?
pass a parameter into getDisplayValue() function like this
getDisplayValue(char c)
and change your function definition to :
public String getDisplayValue(char c)
{
if(c == 'h'){
if(value < 10) {
return "0" + value;
}
else {
return "" + value;
}
}
else if(c=='m'){
return value*60;
}
}
and change updateDisplay() to :
private void updateDisplay()
{
displayString = hours.getDisplayValue(h) + ":" +
minutes.getDisplayValue(m);
}
Introduce a boolean parameter in the function declaration
public String getDisplayValue(Boolean isMinute)
{
if(isMinute)
{
if(value < 10) {
return "0" + value;
}
else {
return "" + value;
}
}
else{
// not a minute, continue
}
}
you can call this like
displayString = hours.getDisplayValue(false) + ":" +
minutes.getDisplayValue(true);
i will added a boolean flag in ClockDisplay i.e. isHour. And will change the constructure:
class ClockDisplay{
boolean isHour;
public ClockDisplay(boolean isHour)
{
hours = new NumberDisplay(24);
minutes = new NumberDisplay(60);
updateDisplay();
this.isHour=isHour;
}
...........
...........
}
Now in NumberDisplay i will change the method:
public String getDisplayValue(ClockDisplay c)
{
if(value < 10) {
return "0" + value;
}
else {
return "" + value;
}
c.
}
Now inside the method getDisplayValue() you can call any method on top of c, and it can print accordingly because you have set isHour accordingly.
The reason behind my design is: The abstraction whether hour or minute it should be encapsulated inside ClockDisplay. So just pass the ClockDisplay reference to getDisplayValue().
You can introduce 2 sub-classes
public class HourDisplay extends NumberDisplay {
// override getDisplayValue method the way you want
}
public class MinuteDisplay extends NumberDisplay {
// override getDisplayValue method the way you want
}
Then in ClockDisplay constructor
public ClockDisplay()
{
hours = new HourDisplay(24);
minutes = new MinuteDisplay(60);
updateDisplay();
}