Display multiple String items Java - java

I have a last Java homework task, this task is about employees,
my method should print employee's names and surnames, worked more than "n" years.
What I've done for now:
public class LastTask {
public static void main(String[] args) {
Employee employee1 = new Employee("Dobrobaba", "Irina", "Ivanovna",
"Moskva", 1900, 6);
Employee employee2 = new Employee("Shmal", "Anna", "Nikolaevna",
"Krasnodar", 2017, 8);
Employee employee3 = new Employee("Kerimova", "Niseimhalum", "Magomedmirzaevna",
"New-York", 2010, 3);
Employee employee4 = new Employee("Dobryden", "Yuri", "Viktorovich",
"Auckland", 2000, 11);
Employee employee5 = new Employee("Lopata", "Leonid", "Nikolaevich",
"Beijing", 2014, 11);
}
/**
* Prints employees' information, which have worked more than 'n' year(s) for now.
*
* #param n years quantity
* #return the String, contained surname, name, patronymic and address of the specific employee(s).
*/
public static String displayEmployees(int n) {
return null;
}
}
class Employee {
private String surname;
private String name;
private String patronymic;
private String address;
private int employmentYear;
private int employmentMonth;
Employee(String surname, String name, String patronymic, String address, int employmentYear, int employmentMonth) {
this.surname = surname;
this.name = name;
this.patronymic = patronymic;
this.address = address;
this.employmentYear = employmentYear;
this.employmentMonth = employmentMonth;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPatronymic() {
return patronymic;
}
public void setPatronymic(String patronymic) {
this.patronymic = patronymic;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getEmploymentYear() {
return employmentYear;
}
public void setEmploymentYear(int employmentYear) {
this.employmentYear = employmentYear;
}
public int getEmploymentMonth() {
return employmentMonth;
}
public void setEmploymentMonth(int employmentMonth) {
this.employmentMonth = employmentMonth;
}
}
I made a parametrised constructor for creating employees with multiple parameters, also made parameters encapsulated.
Have no clue what to do next, task says that I can use List/ArrayList, but after some time googling about it, I still can't understand how to implement a condition like if (employmentYear - currentYear >= n) then return employee1, employee4 for example.
Could you give me some tips?
Thank you for your attention.

You can create a static ArrayList and add those all employees to that ArrayList, and in displayEmployees method you can stream that list based on condition if employee EmploymentYear greater than n print details and add to another list so finally if you want you can just return count of employees or you can return List of employees also
public class LastTask {
static List<Employee> employee = new ArrayList<>();
public static void main(String[] args) {
Employee employee1 = new Employee("Dobrobaba", "Irina", "Ivanovna",
"Moskva", 1900, 6);
Employee employee2 = new Employee("Shmal", "Anna", "Nikolaevna",
"Krasnodar", 2017, 8);
Employee employee3 = new Employee("Kerimova", "Niseimhalum", "Magomedmirzaevna",
"New-York", 2010, 3);
Employee employee4 = new Employee("Dobryden", "Yuri", "Viktorovich",
"Auckland", 2000, 11);
Employee employee5 = new Employee("Lopata", "Leonid", "Nikolaevich",
"Beijing", 2014, 11);
employee.add(employee1);
employee.add(employee2);
employee.add(employee3);
employee.add(employee4);
employee.add(employee5);
}
/**
* Prints employees' information, which have worked more than 'n' year(s) for now.
*
* #param n years quantity
* #return the String, contained surname, name, patronymic and address of the specific employee(s).
*/
public static int displayEmployees(int n) {
List<Employee> finalList = new ArrayList<>();
employee.stream().forEach(emp->{
if(emp.getEmploymentYear()-Year.now().getValue()>=n) {
System.out.println("Employee Name : "+emp.getName()+" Sur Aame : "+emp.getSurname());
finalList.add(emp);
}
});
return finalList.size();
}
}

If you are looking for a way to find "worked more than 'n' years", this might help you.
Calendar.getInstance().get(Calendar.YEAR) - employmentYear >= n

Add a proper toString() method in the Employee class to get the desired output, apart from that I have used the filter() method from the Stream object to filter through the Employee objects. I am passing the number of years worked as an input parameter and calculating the years served in employment from the employmentYear field.
package com.company;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;
public class LastTask {
private static List<Employee> listEmps;
public static void main(String[] args) {
Employee employee1 = new Employee("Dobrobaba", "Irina", "Ivanovna",
"Moskva", 1900, 6);
Employee employee2 = new Employee("Shmal", "Anna", "Nikolaevna",
"Krasnodar", 2017, 8);
Employee employee3 = new Employee("Kerimova", "Niseimhalum", "Magomedmirzaevna",
"New-York", 2010, 3);
Employee employee4 = new Employee("Dobryden", "Yuri", "Viktorovich",
"Auckland", 2000, 11);
Employee employee5 = new Employee("Lopata", "Leonid", "Nikolaevich",
"Beijing", 2014, 11);
listEmps = new ArrayList<>(Arrays.asList(employee1,employee2,employee3,employee4,employee5));
//display employee details of employees who worked more than 17 years.
displayEmployees(17);
}
/**
* Prints employees' information, which have worked more than 'n' year(s) for now.
*
* #param n years quantity
* #return the String, contained surname, name, patronymic and address of the specific employee(s).
*/
public static void displayEmployees(int n) {
int year = Calendar.getInstance().get(Calendar.YEAR);
listEmps.stream()
.filter(emp ->{
return year - emp.getEmploymentYear() > n;
})
.collect(Collectors.toList())
.forEach(System.out::println);
}
}
class Employee {
private String surname;
private String name;
private String patronymic;
private String address;
private int employmentYear;
private int employmentMonth;
Employee(String surname, String name, String patronymic, String address, int employmentYear, int employmentMonth) {
this.surname = surname;
this.name = name;
this.patronymic = patronymic;
this.address = address;
this.employmentYear = employmentYear;
this.employmentMonth = employmentMonth;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPatronymic() {
return patronymic;
}
public void setPatronymic(String patronymic) {
this.patronymic = patronymic;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getEmploymentYear() {
return employmentYear;
}
public void setEmploymentYear(int employmentYear) {
this.employmentYear = employmentYear;
}
public int getEmploymentMonth() {
return employmentMonth;
}
public void setEmploymentMonth(int employmentMonth) {
this.employmentMonth = employmentMonth;
}
#Override
public String toString(){
return "Employee details: " + this.name + this.surname + this.address + this.employmentYear;
}
}

Related

Convert POJO to POJO with custom converter using json configuration

We have two Pojo files.
Person {
String name;
int age;
String address;
String phoneNo;
boolean isMarried;
}
and
OtherPerson {
//mandatory fields are name and age
String name_other;
int age_other;
//other fields
Map<String, Object> otherFields;
}
and a json file which defines the mapping between the fields using name
mappingJson {
"name":"name_other",
"age":"age_other",
"address":"address_other",
"phoneNo":"phoneno_other",
"isMarried":"ismarried_other"
}
Please let me know the best approach to convert Person to OtherPerson. So that the mandatory fields map to name_other and age_other while the other fields should be added to the map(otherFields)
It may be
Person->Person(json)->OtherPerson
Or Person->OtherPerson.
EDIT:
"Use case: We have an API which used to accepts a POJO 'A' but now it needs to accept POJO 'B' as an input argument. This POJO needs to get converted into POJO 'A' which can then be used for persisting into the database. Also POJO 'B' is not under our control"
That's a perfect fit for Jackson Converter! :)
It could work like this:
class OtherPerson {
#JsonProperty("name")
public String name_other;
#JsonProperty("age")
public int age_other;
Map<String, Object> otherFields = new LinkedHashMap<>();;
#JsonAnySetter
public void add(String key, Object value) {
otherFields.put(key, value);
}
}
// ...
Person person = new Person();
person.name = "Avinash";
person.age = 25;
person.address = "Mumbai";
person.phoneNo = "910731";
person.isMarried = true; // :( sorry ladies!
// ...
ObjectMapper mapper = new ObjectMapper();
// If we cannot put #JsonAutoDetect on top of Person.class,
// we need to add handling of non-public fields
// since Person seems to neither have public fields nor setters
mapper.configOverride(Person.class)
.setVisibility(JsonAutoDetect.Value.defaultVisibility()
.withFieldVisibility(JsonAutoDetect.Visibility.NON_PRIVATE));
OtherPerson other = mapper.convertValue(person, OtherPerson.class);
VoilĂ !
I personally would do this without JSON. It's my understanding that some fields in the Map are optional while name and age are mandatory. In the case of the optional content, I would use the Ternary operator to create the person object. This allows you to add some default value if the optional field is not available.
Main
import java.util.HashMap;
import java.util.Map;
/**
*
* #author blj0011
*/
public class JavaApplication30 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Map<String, Object> map1 = new HashMap();
map1.put("address", "123 Hello Street");
map1.put("phoneNo", "555-555-5555");
map1.put("isMarried", true);
OtherPerson otherPerson = new OtherPerson("John Doe", 22, map1);
Map<String, Object> map2 = new HashMap();
map2.put("address", "4456 Bye Road");
map2.put("isMarried", false);
OtherPerson otherPerson2 = new OtherPerson("Jane Doe", 21, map2);
Person person1 = new Person(otherPerson.getName_other(), otherPerson.getAge_other(),
otherPerson.getOtherFields().containsKey("address") ? otherPerson.getOtherFields().get("address").toString(): "",
otherPerson.getOtherFields().containsKey("phoneNo") ? otherPerson.getOtherFields().get("phoneNo").toString(): "",
otherPerson.getOtherFields().containsKey("isMarried") ? Boolean.valueOf(otherPerson.getOtherFields().get("isMarried").toString()): false);
System.out.println(person1);
Person person2 = new Person(otherPerson2.getName_other(), otherPerson2.getAge_other(),
otherPerson2.getOtherFields().containsKey("address") ? otherPerson2.getOtherFields().get("address").toString(): "",
otherPerson2.getOtherFields().containsKey("phoneNo") ? otherPerson2.getOtherFields().get("phoneNo").toString(): "",
otherPerson2.getOtherFields().containsKey("isMarried") ? Boolean.valueOf(otherPerson2.getOtherFields().get("isMarried").toString()): false);
System.out.println(person2);
}
}
Person
/**
*
* #author blj0011
*/
public class Person {
private String name;
private int age;
private String address;
private String phoneNo;
private boolean isMarried;
public Person(String name, int age, String address, String phoneNo, boolean isMarried) {
this.name = name;
this.age = age;
this.address = address;
this.phoneNo = phoneNo;
this.isMarried = isMarried;
}
public boolean isIsMarried() {
return isMarried;
}
public void setIsMarried(boolean isMarried) {
this.isMarried = isMarried;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
#Override
public String toString() {
return "Person{" + "name=" + name + ", age=" + age + ", address=" + address + ", phoneNo=" + phoneNo + ", isMarried=" + isMarried + '}';
}
}
OtherPerson
/**
*
* #author blj0011
*/
public class OtherPerson {
//mandatory fields are name and age
private String name_other;
private int age_other;
//other fields
private Map<String, Object> otherFields;
public OtherPerson(String name_other, int age_other, Map<String, Object> otherFields) {
this.name_other = name_other;
this.age_other = age_other;
this.otherFields = otherFields;
}
public Map<String, Object> getOtherFields() {
return otherFields;
}
public void setOtherFields(Map<String, Object> otherFields) {
this.otherFields = otherFields;
}
public String getName_other() {
return name_other;
}
public void setName_other(String name_other) {
this.name_other = name_other;
}
public int getAge_other() {
return age_other;
}
public void setAge_other(int age_other) {
this.age_other = age_other;
}
}
Output
Person{name=John Doe, age=22, address=123 Hello Street, phoneNo=555-555-5555, isMarried=true}
Person{name=Jane Doe, age=21, address=4456 Bye Road, phoneNo=, isMarried=false}
As you can see in the output OtherPerson2 did not have a phone number. Empty string was use as the default value.

why i got overriding output using arraylist in java? [duplicate]

This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 4 years ago.
i got overriding output on this blockcode
i don't understand why
when inputs are different,
i try to print my arraylist but it print twice
the last employeer
public class Emplyee {
private String name;
private String surname;
private int age;
private String address;
public Emplyee() {
}
public Emplyee(String name, String surname, int age, String address) {
this.name = name;
this.surname = surname;
this.age = age;
this.address = address ;
}
public void setName(String name) {
this.name = name;
}
public void setSurname(String surname) {
this.surname = surname;
}
public void setAge(int age) {
this.age = age;
}
public void setAddress(String address) {
this.address = address;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public int getAge() {
return age;
}
public String getAddress() {
return address;
}
#Override
public String toString() {
return "Emplyee [Name = " + name + ", Surname = " + surname +
", Age = " + age + ", Address = " + address + "]";
}
}
main class
import java.io.*`enter code here`
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws Exception {
Emplyee emplyee = new Emplyee();
ArrayList<Emplyee> listAll=new ArrayList<>();
Scanner sc = new Scanner(System.in);
System.out.println("Do you want to add an Employee?"
+ "\nType 1 for Yes and 0 for Exit");
while(sc.nextInt()!=0) {
if (sc.nextInt()==1) {
emplyee.getName();
System.out.println ("Name: ");
emplyee.setName(sc.next());
emplyee.getSurname();
System.out.println ("Surname: ");
emplyee.setSurname(sc.next());
emplyee.getAge();
System.out.println ("Age: ");
emplyee.setAge(sc.nextInt());
emplyee.getAddress();
System.out.println ("Address: ");
emplyee.setAddress(sc.next());
listAll.add(emplyee);
}
// return employees one by one
for (Emplyee employee : listAll) {
System.out.println(employee.toString());
}
}
//this print output in a .txt file
PrintWriter pw = new PrintWriter("Output.txt");
pw.println(listAll);
pw.flush();
pw.close();
System.out.println("Done!");
}
}
i put twice diferent data
// output is :
Emplyee [Name = hysa, Surname = sdas, Age = 1, Address = durres]
Emplyee [Name = hysa, Surname = sdas, Age = 1, Address = durres]
The reason you keep getting duplicate entries is because, while you are creating a new Employee object, you're only doing it once. This means that you will keep modifying the same object per iteration and those changes are reflected in listAll. Make the following change in your while loop:
while(sc.nextInt()!=0) {
if (sc.nextInt()==1) {
// create new employee per iteration
Emplyee emplyee = new Emplyee ( );
emplyee.getName();
System.out.println ("Name: ");
emplyee.setName(sc.next());
...
By creating a new employee object per iteration, the list can now be populated with unique employees.
Also, emplyee.getName() isn't being used in a practical sense, so unless you plan to do something with this later, you can remove it to "speed up" your program

Filter an ArrayList via Optional in Java 8

I am getting an exception while trying to filter and iterate over a Optional using Java 8. I have an object Subject which is being added in an array list and a value of null also.
Problem Statement: I have an ArrayList, I want to iterate it, filter it and then based on that, only print that record which fulfills the condition.
package com.example.app;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class OptionalTest {
public static void main(String[] args) {
System.out.println("getSubject: " + getSubjects());
// print the Subject with the name "Math"
System.out.println("getSubject " + getSubjects().filter((Subject s) -> s.getName().equalsIgnoreCase("Math")));
}
private static Optional getSubjects() {
Subject subject1 = new Subject(1, "Math", (short)2, "");
Subject subject2 = new Subject(2, "Social Science", (short)4, "Social Science");
Subject subject3 = new Subject(3, "English", (short)6, "Literature");
List<Subject> subjects = new ArrayList<>();
Optional<List<Subject>> optional = Optional.of(subjects);
subjects.add(subject1);
subjects.add(subject2);
subjects.add(null);
subjects.add(subject3);
return optional;
}
}
class Subject {
int id;
String name;
short type;
String description;
public Subject(int id, String name, short type, String description) {
this.id = id;
this.name = name;
this.type = type;
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public short getType() {
return type;
}
public void setType(short type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "\nSubject{" + "id=" + id + ", name=" + name + ", type=" + type + ", description=" + description + '}'+"\n";
}
}
Using Optional.filter would be used to filter List instances as per your code snippet. This is not what you want:
Optional.of(getSubjects()).filter(predicate) //filters lists, not subjects in lists
Your intention is probably to use the a list of Subject objects, then filter. It's the filter method of the Stream interface that returns an Optional instance:
I'd change this method:
private static List<Subject> getSubjects(){
Subject subject1 = new Subject(1, "Math", (short)2, "");
Subject subject2 = new Subject(2, "Social Science", (short)4, "Social Science");
Subject subject3 = new Subject(3, "English", (short)6, "Literature");
List<Subject> subjects = new ArrayList<>();
subjects.add(subject1);
subjects.add(subject2);
subjects.add(null);
subjects.add(subject3);
return subjects;
}
And then use it as follows:
Optional<Subject> filtered = getSubjects()
.stream().filter(s -> s.getName().equalsIgnoreCase("Math"))
//Find first is just one of the many Stream methods
//returning an optional
//It's correct to use it in this case because you know
//only one value is expected to match the filter predicate.
.findFirst();
In fact, if you expect more than one subject to match your filter, you should collect, instead, instead of picking one. In this case, you don't need an optional:
List<Subject> mathSubjects = getSubjects()
.stream().filter((s -> s.getName().equalsIgnoreCase("Math")))
.collect(Collectors.toList());
You can do it very simply using lambda expression, I am providing you a sample so that you can modify according to your need.
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class Java8Optional {
public static void main(String[] args) {
List<Employee> employeeList = new ArrayList<>();
employeeList.add(new Employee(1, "syed"));
employeeList.add(new Employee(2, "az"));
employeeList.add(null);
employeeList.add(new Employee(4, "Rof"));
employeeList.forEach(n -> Optional.ofNullable(n).ifPresent(e -> System.out.println("Employee ID="+e.employeeId+"\tEmployee Name="+e.employeeName)));
}
static class Employee {
Integer employeeId;
String employeeName;
public Integer getEmployeeId() {
return employeeId;
}
public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public Employee(Integer employeeId, String employeeName) {
super();
this.employeeId = employeeId;
this.employeeName = employeeName;
}
}
}

Java Store multiple phone number for one user

Question: Store more than 1 user data with id, name, weight, age, and phone number (can have multiple phone number)
How do I store multiple phone number for one user?
I facing an error "Exception in thread "main" java.lang.NullPointerException at Store_User.main(Store_User.java:29). Anyone can solve it?
import java.util.List;
public class User {
private int usrid;
private String name;
private double weight;
private int age;
private List<String> Pnum;
public User(int usrid, String name, double weight, int age, List<String> Pnum){
this.usrid = usrid;
this.name = name;
this.weight = weight;
this.age = age;
}
public void setUsrid(int usrid) {
this.usrid = usrid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<String> getPnum() {
return Pnum;
}
public void setPnum(List<String> pnum) {
Pnum = pnum;
}
int getUID(){
return usrid;
}
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
public class Store_User {
public static void main(String[] args) {
User usr1 = new User(1,"Mark", 55.5, 26, Arrays.asList("0140392812", "0123456789"));
User usr2 = new User(2, "Ken", 54.7, 33, Arrays.asList("0129876543"));
User usr3 = new User(3, "Callie", 62.3, 34, Arrays.asList("06123456", "0987654322", "01798654321"));
ArrayList<User> ulist = new ArrayList<User>();
ulist.add(usr1);
ulist.add(usr2);
ulist.add(usr3);
Iterator itr=ulist.iterator();
while(itr.hasNext()){
User usr = (User)itr.next();
System.out.println(usr.getUID() +", " + usr.getName() +", " + usr.getAge() +", " + usr.getWeight());
String out ="";
for(String number: usr.getPnum()){
out += number + ";";
}
System.out.println(out);
}
}
}
Chat conversation end
EDIT: Phone numbers are stored as an ArrayList of Strings and are "linked" to the usrId since they are non-static members of the same class, hence each User object will have it's own id and list of numbers. You can access the phone numbers of a user using:
usr.getPnum()
where usr is an instance of User.java, this will return a ArrayList<String> representing the phone numbers, if you want a specific number you can access the list by index like so:
usr.getPnum().get(0) //The index in this case is 0
User.java
import java.util.List;
public class User {
private int usrid;
private String name;
private double weight;
private int age;
private List<String> Pnum;
public User(int usrid, String name, double weight, int age, List<String> Pnum){
this.usrid = usrid;
this.name = name;
this.weight = weight;
this.age = age;
this.Pnum = Pnum;
}
public void setUsrid(int usrid) {
this.usrid = usrid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<String> getPnum() {
return Pnum;
}
public void setPnum(List<String> pnum) {
Pnum = pnum;
}
int getUID(){
return usrid;
}
}
Store_User.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
public class Store_User {
public static void main(String[] args) {
User usr1 = new User(1,"Tee Ting Ong", 55.5, 26, Arrays.asList("00000000", "00000000", "00000000"));
User usr2 = new User(2, "Tee Soon Teh", 54.7, 33, Arrays.asList("00000000", "00000000"));
User usr3 = new User(3, "Tee Ting Ken", 62.3, 34, Arrays.asList("00000000"));
ArrayList<User> ulist = new ArrayList<User>();
ulist.add(usr1);
ulist.add(usr2);
ulist.add(usr3);
Iterator itr=ulist.iterator();
while(itr.hasNext()){
User usr = (User)itr.next();
System.out.println(usr.getUID() +", " + usr.getName() +", " + usr.getAge() +", " + usr.getWeight());
//This print out the numbers
String out = "";
for(String number : usr.getPnum()){
out += number + ";";
}
System.out.println(out);
}
}
}

Array sorting printing and summing

What would be the simplest method to print this array broken down into each mobile phone as a product number, name department etc, and then re print the same information sorted by product name. I have tried a couple different methods and am already passed the turn in date for the assignment but still need to figure it out for upcoming assignment this weekend. When I try to implement the comparator on MobilePhone class it forces me to make it abstract or use #override but I can't figure out where or what to override to make it work because the abstract class causes a multitude of other problems.
package InventoryPro2;
import java.util.*;
class MobilePhone {
private double productNumber; // Variables
private String name;
private String department;
private double unitsInStock;
private double unitPrice;
public MobilePhone() {
this(0.0, "", "", 0.0, 0.0);
}
public MobilePhone(double productNumber, String name, String department,
double unitsInStock, double unitPrice) { //assign variables
this.productNumber = productNumber;
this.name = name;
this.department = department;
this.unitsInStock = unitsInStock;
this.unitPrice = unitPrice;
}
public double getproductNumber() { // retrieve values
return productNumber;
}
public String getname() {
return name;
}
public String getdepartment() {
return department;
}
public double getunitPrice() {
return unitPrice;
}
public double getunitsInStock() {
return unitsInStock;
}
public void setproductNumber(double productNumber) {
this.productNumber = productNumber;
}
public void setname(String name) {
this.name = name;
}
public void setdepartment(String department) {
this.department = department;
}
public void setunitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public void setunitsInStock(double unitsInStock) {
this.unitsInStock = unitsInStock;
}
public double gettotalInv() {
return getunitPrice() * getunitsInStock();
}
}
public class InventoryPro2 {
MobilePhone mobilephone = new MobilePhone();
public static void main(String args[]) {
System.out.println("Mobile Phone Inventory Program");
System.out.println();//skips a line
MobilePhone[] phones = new MobilePhone[5];
phones[0] = new MobilePhone();
phones[0].setproductNumber(1);
phones[0].setname("Motorola");
phones[0].setdepartment("Electronics");
phones[0].setunitPrice(150.10);
phones[0].setunitsInStock(98);
phones[1] = new MobilePhone();
phones[1].setproductNumber(2);
phones[1].setname("Samsung");
phones[1].setdepartment("Electronics");
phones[1].setunitPrice(199.99);
phones[1].setunitsInStock(650);
phones[2] = new MobilePhone();
phones[2].setproductNumber(3);
phones[2].setname("Nokia");
phones[2].setdepartment("Electronics");
phones[2].setunitPrice(200.25);
phones[2].setunitsInStock(125);
phones[3] = new MobilePhone();
phones[3].setproductNumber(4);
phones[3].setname("LG");
phones[3].setdepartment("Electronics");
phones[3].setunitPrice(100.05);
phones[3].setunitsInStock(200);
phones[4] = new MobilePhone();
phones[4].setproductNumber(5);
phones[4].setname("IPhone");
phones[4].setdepartment("Electronics");
phones[4].setunitPrice(299.99);
phones[4].setunitsInStock(150);
System.out.println("Order of inventory before sorting:");
System.out.println();
}
}
(Also, what is the best way to take just one piece of information out of each part of the array such as the totalInv and total all of those numbers to print?) Do I have unnecessary code here or have I done everything right thus far? I have to say that learning this coding language in an online format has not been a very enjoyable experience thus far..
Here is how to sort by name
import java.util.Arrays;
import java.util.Comparator;
public class AppInventoryPro2 {
public static void main(String... args) {
System.out.println("Mobile Phone Inventory Program");
System.out.println();// skips a line
MobilePhone[] phones = new MobilePhone[5];
phones[0] = new MobilePhone();
phones[0].setproductNumber(1);
phones[0].setname("Motorola");
phones[0].setdepartment("Electronics");
phones[0].setunitPrice(150.10);
phones[0].setunitsInStock(98);
phones[1] = new MobilePhone();
phones[1].setproductNumber(2);
phones[1].setname("Samsung");
phones[1].setdepartment("Electronics");
phones[1].setunitPrice(199.99);
phones[1].setunitsInStock(650);
phones[2] = new MobilePhone();
phones[2].setproductNumber(3);
phones[2].setname("Nokia");
phones[2].setdepartment("Electronics");
phones[2].setunitPrice(200.25);
phones[2].setunitsInStock(125);
phones[3] = new MobilePhone();
phones[3].setproductNumber(4);
phones[3].setname("LG");
phones[3].setdepartment("Electronics");
phones[3].setunitPrice(100.05);
phones[3].setunitsInStock(200);
phones[4] = new MobilePhone();
phones[4].setproductNumber(5);
phones[4].setname("IPhone");
phones[4].setdepartment("Electronics");
phones[4].setunitPrice(299.99);
phones[4].setunitsInStock(150);
System.out.println("Order of inventory before sorting:");
System.out.println(Arrays.toString(phones));
Arrays.sort(phones, new Comparator<MobilePhone>() {
#Override
public int compare(MobilePhone mp1, MobilePhone mp2) {
return mp1.getname().compareTo(mp2.getname());
}
});
System.out.println("Order of inventory after sorting by name:");
System.out.println(Arrays.toString(phones));
}
}
class MobilePhone {
private double productNumber; // Variables
private String name;
private String department;
private double unitsInStock;
private double unitPrice;
public MobilePhone() {
this(0.0, "", "", 0.0, 0.0);
}
public MobilePhone(double productNumber, String name, String department,
double unitsInStock, double unitPrice) { // assign variables
this.productNumber = productNumber;
this.name = name;
this.department = department;
this.unitsInStock = unitsInStock;
this.unitPrice = unitPrice;
}
public double getproductNumber() { // retrieve values
return productNumber;
}
public String getname() {
return name;
}
public String getdepartment() {
return department;
}
public double getunitPrice() {
return unitPrice;
}
public double getunitsInStock() {
return unitsInStock;
}
public void setproductNumber(double productNumber) {
this.productNumber = productNumber;
}
public void setname(String name) {
this.name = name;
}
public void setdepartment(String department) {
this.department = department;
}
public void setunitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public void setunitsInStock(double unitsInStock) {
this.unitsInStock = unitsInStock;
}
public double gettotalInv() {
return getunitPrice() * getunitsInStock();
}
#Override
public String toString() {
return "MobilePhone [productNumber=" + productNumber + ", name=" + name
+ ", department=" + department + ", unitsInStock="
+ unitsInStock + ", unitPrice=" + unitPrice + "]";
}
}
1 - To print content of MobilePhone class: Override default toString method like this:
#Override
public String toString() {
return "MobilePhone [productNumber=" + productNumber +
", name=" + name + ']'; // add more info if needed
}
2 - To allow sorting by name: Have MobilePhone class implement Comparable interface like
this:
class MobilePhone implements Comparable {
...
#Override
public int compareTo(Object o) {
MobilePhone m = (MobilePhone) o;
return (this.name.compareTo(o.name));
}
}
EDIT: To print your array of MobilePhone object you can do:
System.out.printf("Phones: %s%n", Arrays.toString(phones));

Categories