One instance variable for multiple values - java

I'm a Java beginner so bear with me
The requirements are only one instance variable, one constructor, and one method is allowed. Is it possible to make description(instance variable, not the constructor) store multiple values for a date(such as year, month and day)? Something like the code below. I can print it fine if there are multiple instance variables but not with one.
import java.util.Date;
public class MyDate {
public Date description; //type might be wrong
public MyDate(int year, int month, int day, String description) {
//not sure what to put
}
public String toString() {
//return d + "/" + m + "/" + y + " " + description;
}
}

There are different way to store your value into one variable.
Store your values in key-value pair using Map.
Store values in simple List or Arrays and retrieve using index.
Make one class include all your required attribute as instant member for that class. Create object of that class set value to
instant variable.
May one this way will help to solved your problem.
Sample Example :
1. Using Map<String,Object> :
public Map<String,Object> description; //type might be wrong
public MyDate(int year, int month, int day, String descriptionTxt) {
description = new HashMap<String, Object>();
description.put("year", year);
description.put("month", month);
description.put("day", day);
description.put("desc", descriptionTxt);
}
2.Using List<Object> :
public List<Object> description; //type might be wrong
public MyDate(int year, int month, int day, String descriptionTxt) {
description = new ArrayList<Object>();
description.add(year);
description.add( month);
description.add(day);
description.add(descriptionTxt);
}
3.Using Class :
class MyClass
{
private int year;
private int month;
private int day;
private String desc;
//Getter and Setter Method
}
//MyDate class
public MyClass description; //type might be wrong
public void MyDate(int year, int month, int day, String descriptionTxt) {
description = new MyClass();
description.setYear(year);
description.setMonth(month);
description.setDay(day);
description.setDesc(descriptionTxt);
}

Related

Java OOP - How to get year in DOB and current year then calculate age?

I have three classes. My driver class, a Person class, and a Chore class.
I have chores and family members listed in two separate csv files.
The family members file just contains names and dob's (01/01/1901).
So the first thing I want to do is calculate each family member's age based on the year in their dob and get the current year then get the difference of the two. How do I select for just the year in each person's dob and how do I get the current year?
public int currentAge(LocalDate dob, LocalDate currentDate){
if ((dob != null) && (currentDate != null)) {
return Period.between(dob, currentDate).getYears();
} else {
return 0;
}
}
public int getCurrentAge(){
return currentAge;
}
To calculate the age of a person from their birthdate, using Java 8+ Time API, use this method:
public static int getAge(LocalDate dob) {
LocalDate today = LocalDate.now();
int age = today.getYear() - dob.getYear();
if (MonthDay.from(today).isBefore(MonthDay.from(dob)))
age--; // before birthday in current year
return age;
}
Java 8 compatible solution :
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
public class Demo
{
public static void main(String[] args)
{
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/yyyy");
String date = "16/08/2016";
LocalDate dob = LocalDate.parse(date, formatter);
System.out.println(daysBetween(dob));
}
private static long daysBetween(LocalDate dob)
{
return Period
.between(dob,
LocalDate.now())
.getYears();
}
}
We can add a data member in the People for holding the chore information.
class People{
private final String name;
private final LocalDate dob;
private final String gender;
private List<Chores> choresList;
}
You can use the following method or something similar to get the age:
private long daysBetween(Date one, Date two) {
long difference = (one.getTime()-two.getTime())/86400000;
return Math.abs(difference);
}
Read more here or here.

How to print Array of Object in java

Assuming there is a Class called Product which has two product object called p1 and p2 which have the following fields:
P1--> int productId =123, String name ="iPhoneS8", int unitPrice
=1000, String datMfs ="12/18/2017". P2--> int productId =124, String name ="Samsung Galaxy S8", int unitPrice =1200, String datMfs
="05/22/2016".
The first question is
1), Write a java code for the product including getters and setters
methods, any three overloaded constructors including default. My
solution code is the following.
class Product {
Product() {//default Constractor
}
Product(int price) {//Overloaded Constractor1
}
Product(String name) {//Overloaded Constractor2
}
Product(String name, double pri) {//Overloaded Constractor3
}
Product(int name, double pri) {//Overloaded Constractor4
}
// The following is the product fields
private int productId;
private String name;
private int unitPrice;
private String dateMdft;
//The following is getters and setters
public int getproductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getproductName() {
return name;
}
public void setProductname(String name) {
this.name = name;
}
public int getproductunitPrice() {
return unitPrice;
}
public void setUnitPrice(int unitPrice) {
this.unitPrice = unitPrice;
}
public int getUnitPrice() {
return unitPrice;
}
public void setDateMan(String dateMdft) {
this.dateMdft = dateMdft;
}
public String getDateManftd(String dateMdft) {
return dateMdft;
}
The second Question is
2), Write a method called printOutedDatedProduct(from the above) and
iterate through the object and print out the data for only the
outdated product to the screen in CSV format. the method should print
124, Samsung Galaxy S8,1200, 5/22/2016.
I am really Struggling to write the method and print out the outdated product so I really appreciate the community if anybody helps me and I am also really open to take any comments as far as the solution to the first question is concerned too. Great Thanks!
I would recommend to store date in LocalDate object. Why LocalDate? It is a well-written and tested class for date mainetenance.
How to instantiate and compare:
LocalDate d1 = LocalDate.of(2000, 06, 26);//YYYY-MM-DD
LocalDate d2 = LocalDate.now();
System.out.println(d1.compareTo(d2));//if d1 < d2, returns negative integer (difference between dates), otherwise positive integer.
What does d1.compareTo(d2)? It returns an integer representing the difference bwtween dates. It takes the first terms of dates that don't match and subtracts the second from the first. For example: 2019-03-14 compared to now (2019-03-29) will return 14-29 = -15.
You need to call compareTo(LocalDate) method for each LocalDate field of Product instance and compare with LocalDate.now();. When the numer is negative, print info about the product.
Java by default calls the toString method when you try to use an object as a String then what you need to do is to prepare the Product toString method first like this below:
public String toString(){
return productId+", "+name+", "+unitPrice+", "+dateMdft;
}
after that, the printing is going to be easy but you need to check for the date, manipulating a date as a String will cost you a lot. you can find java dates best practices presented in a good way here
after you learned how to use the Date class and how to check your date now you all you need to write the function that loops on the array you have and checks the date and print your data.
First, think about right datatypes for fields. You can use String for date filed, but how will you compare this dates? There is powerful JDK datetime API, let's use it. I'll recommend LocaDate, as you need only date part.
Second. Your constructors shouldn't be empty or useless. You could initialize object fields in constructors. For example:
Product(String name) {
this(name, 0);
}
Product(String name, int unitPrice) {
this(name, unitPrice, LocalDate.now());
}
Product(String name, int unitPrice, LocalDate dateMdft) {
this.name = name;
this.unitPrice = unitPrice;
this.dateMdft = dateMdft;
}
The next step is method for string representation of object. You could override toString or create another.
private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM/dd/YYYY");
#Override
public String toString() {
return productId + "," + name + "," + unitPrice + "," + dateTimeFormatter.format(dateMdft);
}
And the last, filter and print.
public static void main(String args[]) {
List<Product> products = new ArrayList<>();
products.add(new Product("1", 100, LocalDate.now().minusDays(1)));
products.add(new Product("2", 150, LocalDate.now().minusDays(2)));
products.add(new Product("3", 250, LocalDate.now()));
System.out.println("Via for loop:");
for (Product p: products) {
if (p.getDateMdft().isBefore(LocalDate.now())) {
System.out.println(p);
}
}
System.out.println("Via stream API:");
products
.stream()
.filter(p -> p.getDateMdft().isBefore(LocalDate.now()))
.forEach(System.out::println);
}

How do I add an item from a class to an ArrayList?

I know the question seems weird, but I'll try to explain it the best that I can. I am doing an Amusement Park Project where you have methods for the tickets, merchandise, etc. I made a Ticket class with the methods, but now I'm in the AmusementPark class trying to create a method of taking the date from that class and putting it into a new ArrayList. Maybe my code will help explain it.
First, here is my Ticket class......
import java.text.DecimalFormat;
public class Ticket {
private long number;
private String category;
private String holder;
private String date;
private double price;
private boolean purchased;
Ticket(long num, String cat, String h, String dt, double pr, boolean pch){
this.number= num;
this.category= cat;
this.holder= h;
this.date= dt;
this.price= pr;
this.purchased= pch;
}
long getNumber(){
return number;
}
String getCategory(){
return category;
}
String getHolder(){
return holder;
}
String getDate(){
return date;
}
boolean getPurchased(){
return purchased;
}
double getPrice(){
return price;
}
void setPrice(double pr){
price= pr;
}
void setChangePurchased(boolean newStatus){
purchased= newStatus;
}
#Override
public String toString(){
DecimalFormat dm= new DecimalFormat("#.##");
String disp;
disp = "Number: " + getNumber() + "\nCategory: " + getCategory() + "\nTicket Holder Name: " + getHolder() + "\nDate: " + getDate()
+ "\nPrice: " + dm.format(getPrice()) + "\nPuchased Completed?: " + purchased;
return disp;
}
}
Here is some of the Pseudo Code explaining what I am trying to do with the next class I'm about to post.
Create an ArrayList from the Ticket class.
//The ticket class has the following constructors....
// (Ticket number of type long, category of type String, Ticket holder of type String, Date of admission, purchase price of type double, variable named "purchased" whether the ticket has been paid for of type boolean)
//One of the variables of type class is tickets in which the ticket class is made into an ArrayList.
//The next task is to get tickets for dates where they are available, which is done by searching tickets where the purchase is not completed.
Create a public ArrayList<Date> method called getTicketDates(){
Create a variable called theDateArray which is a new ArrayList<Date>;
For(starting at the first position of the list, go through the the entire list incrementing by one){
if (boolean purchased of the Ticket ArrayList is false)**{
Add the date of the object from the Ticket ArrayList to theDateArray ArrayList.}** //This stores the dates of all tickets not yet purchased into the new ArrayList.
}
Return theDateArray;
}
//The next task is to search through theDateArray for only select dates and post the available tickets for that date as an integer.
Create a method which displays the number of tickets for a specified date by going through theDateArray (Date date) {
For(starting at the first position of theDateArray, go through the entire list and look for tickets that have a particular date){
if (the date== entered date){
Include the ticket as one of the tickets available for that date.
}
}
Return the total number of tickets available for that date as a type integer.
}
Okay, now here is my AmusementPark class. Note It is not finished. I'm just trying to get this one part done....
import java.util.ArrayList;
import java.util.Date;
public class AmusementPark {
private ArrayList<Ticket> tickets;
private ArrayList<Merchandise> merchandise;
private String name;
AmusementPark(String name){
this.name=name;
this.tickets = new ArrayList<Ticket>();
this.merchandise= new ArrayList<Merchandise>();
}
String getName(){
return name;
}
public ArrayList<String> getTicketDates(){
ArrayList<String> theDateArray= new ArrayList<>();
int i;
String date = Ticket.getDate(); //This is not working. See Reason Below.
for (i=0; i<tickets.size(); i++){
if(tickets.get(i).getPurchased()== false){
theDateArray.add(date);
}
}return theDateArray;
}
}
Okay, so now what happens when I try to call the method of getDate() from the Ticket class, it's not allowing me to use it for the reason that I cannot make a static reference to a non-static method. However, when I try to make the method static, it messes up the other class by saying I cannot make a static reference to a non-static field.
An ArrayList of the Ticket class has already been made. I need it to scroll through that list, get the ones where the boolean is false, and add the date to the next ArrayList.
Does this at all make sense?
Any ideas that would be better?
Let's take your method.
public ArrayList<String> getTicketDates(){
ArrayList<String> theDateArray= new ArrayList<>();
int i;
String date = Ticket.getDate(); //This is not working. See Reason Below.
for (i=0; i<tickets.size(); i++){
if(tickets.get(i).getPurchased()== false){
theDateArray.add(date);
}
}
return theDateArray;
}
Notice the problem on the Ticket.getDate() that you try to do whithout an instance, so a static call. But what you explain, you want the date for the Ticket of the list tickets. Good, you are iterating it after but are pushing this strange value date coming from a "static method".
You problem is that the instance holding the date you want is in the list. You are using it to see if it is purchased or not. So call the method on those instance to get the value :
for (i=0; i<tickets.size(); i++){
if(tickets.get(i).getPurchased()== false){
theDateArray.add(tickets.get(i).getDate());
}
}
But better :
Ticket ticket;
for (i=0; i<tickets.size(); i++){
ticket = tickets.get(i);
if(ticket.getPurchased()== false){
theDateArray.add(ticket.getDate());
}
}
If I understand it correctly what is required here is to extract dates for not purchased tickets into separate dates array. And you already got it correctly in your pseudocode, you just need to follow it more strictly during implementation:
public ArrayList<String> getTicketDates() {
ArrayList<String> theDateArray = new ArrayList<>();
// iterate over all tickets
for ( Ticket ticket : tickets ) {
// if ticket not purchased
if ( ! ticket.getPurchased() ) {
// add ticket's date into array
theDateArray.add( ticket.getDate() );
}
}
return theDateArray;
}
DON'T MAKE STATIC REFERENCE !Instead of writing a what's code answer let's focus on the workaround of problem.
Whenver you will set values to instance variables of TICKET Class it will refer to a particular object (new ticket()) to access its values if you make variables of class staticValues will be stored when class is loaded and not when object is created but arraylist items need to have
Object of ticket Class.
A simple approach should be
ASSIGN THE VALUES TO VARIABLES WHEN EVER YOU MAKE AN OBJECT OF TICKET CLASS BY BY PASSING VALUES IN ITS CONSTRUCTOR AND THEN
ADD THOSE OBJECTS TO ARRAYLISTITEMS
ticket class
public class Ticket {
private long number;
private String category;
private String holder;
private String date;
private double price;
private boolean purchased;
Ticket(long num, String cat, String h, String dt, double pr, boolean pch){
this.number= num;
this.category= cat;
this.holder= h;
this.date= dt;
this.price= pr;
this.purchased= pch;
}
make a new object and pass values
Ticket t1=new Ticket(3,"yourstring","yourstring",yourDouble,true/false);
add items in arrayliSt:
List<Tickets> tList=new ArrayList();
tList.add(t1);
tList.add(t2);
//and so on
now retrive values from arralylist
Ticket t=tlist.get(0);
t.cat;
t.whatevrbe thevalue be

Calculated value in Groovy enum

I need to create an enum or a class that has some predefined values and must have an option to calculate other values. Say we have this enum:
enum Duration {
ONE_HOUR("1${DurationUnits.DURATION_SUFFIX_HOUR}"),
ONE_DAY("24${DurationUnits.DURATION_SUFFIX_HOUR}"),
ONE_WEEK("7${DurationUnits.DURATION_SUFFIX_DAY}"),
ONE_MONTH("30${DurationUnits.DURATION_SUFFIX_DAY}")
String duration
Environment(String duration) {
this.duration = duration
}
static String custom(Date startTime, Date endTime) {
// TODO Calculate difference in days between the two dates
}
private static class DurationUnits {
public static final String DURATION_SUFFIX_HOUR = "h"
public static final String DURATION_SUFFIX_DAY = "d"
}
}
So my question is if I can define an enum value, say CUSTOM, that represents the value of all the non predefined ones. That is, a generic value for the custom(Date a, Date b) method.
I can't figure out how to do it, actually I don't think it's even possible.
As an alternative I'm thinking of creating a class instead of an enum, like this:
class Duration {
private static final String DURATION_SUFFIX_HOUR = "h"
private static final String DURATION_SUFFIX_DAY = "d"
/** Predefined values */
static final String ONE_HOUR = "1${DURATION_SUFFIX_HOUR}"
static final String ONE_DAY = "24${DURATION_SUFFIX_HOUR}"
static final String ONE_WEEK = "7${DURATION_SUFFIX_DAY}"
static final String ONE_MONTH = "30${DURATION_SUFFIX_DAY}"
static String custom(Date startDate, Date endDate) {
// TODO Calculate difference in days between the two dates
}
}
What do you think is the best way to go? This duration will be an input parameter to a method that calls a REST web service, that's why I was trying to define it as an enum instead of just passing a string.
You can use String append.
ONE_HOUR("1" + DurationUnits.DURATION_SUFFIX_HOUR),
ONE_DAY("24" + DurationUnits.DURATION_SUFFIX_HOUR),
ONE_WEEK("7" + DurationUnits.DURATION_SUFFIX_DAY),
ONE_MONTH("30" + DurationUnits.DURATION_SUFFIX_DAY);
However it might be better to use TimeUnits
ONE_HOUR(1, TimeUnit.HOUR),
ONE_DAY(1, TimeUnit.DAY),
ONE_WEEK(7, TimeUnit.DAY),
ONE_MONTH(30, TimeUnit.DAY);
Note: not all months have 30 days.
You can also use Duration for a duration of time.
Duration ONE_HOUR = Duration.ofHours(1);
Duration ONE_DAY = Duration.ofDays(1);
This would allow you to create more Duration as needed.
If it were Java (I'm not a Groovy expert) I'd suggest something like ONE_HOUR("1" + DurationUnits.DURATION_SUFFIX_HOUR), or yet better use another enum that represents the unit itself, e.g. like this:
enum DurationUnit {
HOUR ("k"),
DAY( "d" );
private final String key;
//constructor and getter
}
enum Duration {
ONE_HOUR(1, DurationUnit.HOUR ),
...
private final int quantity;
private DurationUnit unit;
//constructor and getters
public String toString() {
return quantity + unit.getKey(); //should return 1h, 24h, 1d etc.
}
}
This should be doable in Groovy as well and would allow for calculations/comparisons without needing to parse a string.
Update:
For custom durations (and if Java 8's own Duration class doesn't fit your needs) you'd make Duration a normal (immutable) class with some constants:
class Duration {
public static final Duration ONE_HOUR = new Duration(1, DurationUnit.HOUR );
...
private final int quantity;
private DurationUnit unit;
//constructor and getters
}

Passing constructor parameters to initialize an object [duplicate]

This question already has answers here:
How to initialize a reference attribute in a constructor in Java?
(3 answers)
Closed 7 years ago.
I'm writing a java class that borrows elements of another class and need to pass three of the four parameters of the constructor to initialize the other class object. I'm lost as to how to initialize it, though. Any help is much appreciated. Here's what I have right now:
private String name;
private MyDate birthday;
/**
* Constructs a new Person object.
*/
public Person(String name, int month, int day, int year) {
this.birthday = birthday(month, day, year);
this.name = name;
}
This will depend on whether or not the birthday class is connected by some means (extended or friended) or if the birthday.birthday field is publicly accessible.
For example, if you wanted to keep up with good practice. You could set up a
GetBirthday(); method inside of the birthday class and do the following.
private MyDate birthdate;
public Person(String name, int month, int day, int year) {
birthday bDay = new birthday(month, day, year);
this.birthdate = bDay.GetBirthday();
this.name = name;
}
You could also create an inline function birthday() which calculates birthdays, but I would not advise doing it as such.

Categories

Resources