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);
}
Related
In my assignment I have to use an enum to make an EnumSet of elements that fit the criteria given. So, the code needs to be as flexible as possible and allow any criteria that could be applied to the object declared in the enum.
I've been testing things out, my code involves taking the finals of the enum into the static context, so that a boolean can be applied to them, and then looping through each declared object in the enum to see if they fit the criteria. For some reason though, the state of the boolean doesn't change to true, when the value of the static fields fit the criteria.
Here is my code:
public class test {
// enumeration of persons by age and sex
enum Name {
Adam("Male", 17),
Amy("Female", 24),
Boris("Male", 12),
Bella("Female", 16);
final String _sex;
final int _age;
// static variants to "turn" values to the static context
volatile static String sex = "";
volatile static int age = 0;
Name(String sex, int age) {
_sex = sex;
_age = age;
}
}
public static void main(String[] args) {
// creating a set of people older than 17
EnumSet<Name> set = makeSet(Name.age >= 17);
System.out.print(set.toString());
}
static EnumSet<Name> makeSet(boolean query) {
EnumSet<Name> set = EnumSet.noneOf(Name.class);
for (Name element : Name.values()) {
// this is the "turning" of the values to the static context
Name.sex = element._sex;
Name.age = element._age;
// PROBLEM LIES HERE
// the query remains false, even when age is above 17
if (query) {
set.addAll(EnumSet.of(element));
}
}
return set;
}
}
Changing the static fields to volatile doesn't fix the problem either, so I don't think it's a caching issue.
So, why does the boolean not update? Is there a work-around?
The problem you are facing is that the predicate (Name.age >= 17) is checked at the moment of the function call:
When you are calling makeSet(Name.age >= 17), what actually happens is, the predicate returns a boolean, which at the time of checking returns false, and false is therefore parsed into the function.
Answered in comments by #Turing85
The problem occurred because the boolean is being passed by value.
Using a Predicate instead of just a boolean fixed the problem, because the object reference would be passed on instead, allowing the value to change after the makeSet() method was invoked.
Furthermore, this eliminates the need to take the finals of the enum into the static context.
Here is my code now:
public class test {
// enumeration of persons by age and sex
enum Name {
Adam("Male", 17),
Amy("Female", 24),
Boris("Male", 12),
Bella("Female", 16);
final String sex;
final int age;
Name(String sex, int age) {
this.sex = sex;
this.age = age;
}
}
public static void main(String[] args) {
// creating a set of people older than 17
EnumSet<Name> set = makeSet(query -> query.age >= 17);
System.out.print(set.toString());
}
static EnumSet<Name> makeSet(Predicate<Name> query) {
EnumSet<Name> set = EnumSet.noneOf(Name.class);
for (Name element : Name.values()) {
// PROBLEM FIXED
if (query.test(element)) {
set.addAll(EnumSet.of(element));
}
}
return set;
}
}
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
I am new in the Unit Testing.
I have a class Ckeckout which main function is to print the amount to be paid for books. The user types the titles of the books in the command line, and based on some calculations I have to output the final price.
Here is the Book class:
public class Book {
private String title;
private double price;
private int year;
public Book(String title, double price, int year) {
super();
this.title = title;
this.price = price;
this.year = year;
}
}
And here is the Checkout class:
public class Checkout {
private List<Book> books;
public Checkout(List<Book> books) {
super();
this.books = books;
}
//calculate the final price
private double getPrice(){
//return some double
}
}
What I want to test is just getPrice method. However, to do so, do I have to create list of Book objects in my CheckoutTest? Also, I will have to verify the final result with some very long number (like 62.01997301). Isn't it easier, to test the main() method, since in my Unit test, there won't be any need to create the Book objects (I will work only with Strings) and I can verify the output with shorter number (like 62.01)?
However, to do so, do I have to create list of Book objects in my CheckoutTest?:Generally and in any kind - yeah!
Also, I will have to verify the final result with some very long number (like 62.01997301): Naah, this depends on your targeting test/code quality! (for a "price" 2 digits should be sufficient (in any country!?))
Isn't it easier, to test the main() method, since in my Unit test, there won't be any need to create the Book objects (I will work only with Strings) and I can verify the output with shorter number (like 62.01)? Definitely! But with the current setup some (human) would have to check the console for "passing that test", for JUnit(and programmatically testing the value), you should/will need to make "getPrice() more visible" ... or in some way access its value.
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);
}
I'm currently writing a program that should read through a text file, create an array of different types of employees (each have their own subclass), then print out the information in a different format. I think I've got most of it working, but whenever I try to actually create the objects (at least I think that's what it is?), I'm getting a "Constructor is undefined" error. This is happening on all 7 of these objects. I will simply post one here (along with its subclass) so that you guys aren't overloaded with information, and hopefully I can figure out the rest from that.
Thanks for any help you can provide!
Driver class where I'm reading and creating objects (did not include the rest of the code following this)
Error occurs at the "Emp[0]" line
import java.io.File;
import java.util.Scanner;
public class PayrollSystemTest2 {
/**
* #param args
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Scanner input;
input = new Scanner(new File("EmployeePayrollInfo.txt"));
Employee[] Emp = new Employee[20];
while(input.hasNext())
{
String ID = input.nextLine();
if (ID.charAt(0) == 'S')
{
String first = input.nextLine();
String last = input.nextLine();
String ssn = input.nextLine();
Date DayOfBirth = new Date(input.nextInt(),input.nextInt(),input.nextInt());
double salary = input.nextDouble();
Emp[0] = new SalariedEmployee(first, last, ssn, DayOfBirth, ID);
}
SalariedEmployee subclass
public class SalariedEmployee extends Employee
{
private double weeklySalary;
// four-argument constructor
public SalariedEmployee( String first, String last, String ssn, Date DayOfBirth, String ID,
double salary )
{
super( first, last, ssn, DayOfBirth, ID); // pass to Employee constructor
setWeeklySalary( salary ); // validate and store salary
} // end four-argument SalariedEmployee constructor
// set salary
public void setWeeklySalary( double salary )
{
double baseSalary;
if ( salary >= 0.0 )
baseSalary = salary;
else
throw new IllegalArgumentException(
"Weekly salary must be >= 0.0" );
} // end method setWeeklySalary
// return salary
public double getWeeklySalary()
{
return weeklySalary;
} // end method getWeeklySalary
// calculate earnings; override abstract method earnings in Employee
#Override
public double earnings()
{
return getWeeklySalary();
} // end method earnings
// return String representation of SalariedEmployee object
#Override
public String toString()
{
return String.format( "salaried employee: %s\n%s: $%,.2f",
super.toString(), "weekly salary", getWeeklySalary() );
} // end method toString
} // end class SalariedEmployee
Again, thanks for any help you can provide.
Well yes - look at your constructor, including the clearly-inaccurate comment:
// four-argument constructor
public SalariedEmployee(String first, String last, String ssn, Date DayOfBirth,
String ID, double salary)
Note how there are 6 parameters. Now here's how you're trying to call it:
Emp[0] = new SalariedEmployee(first, last, ssn, DayOfBirth, ID);
You're passing in 5 arguments. What happened to the salary?
As side notes:
Java variables are conventionally camelCased - so dayOfBirth and id rather than DayOfBirth and ID
Using double for financial values such as a salary is a bad idea. Use BigDecimal or keep an integer number of cents. (That's assuming you even need it down to the cent...)