Java Store multiple phone number for one user - java

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);
}
}
}

Related

File with multiple data types, into arrays, then sort one array while keeping the records together

My problem is that I will be giving a file with student information: name, age, and GPA. I then have to turn each data element into a separate array. I then have to sort GPA into descending order, while keeping name and age with the corresponding GPA, and then print it out with "Name Age GPA" heading.
Check below code to sort data based on GPA. However you will have to include relevant code for file reading.
Student.java (POJO)
public class Student {
String name;
int age;
double GPA;
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 double getGPA() {
return GPA;
}
public void setGPA(double gPA) {
GPA = gPA;
}
public Student(String name, int age, double gPA) {
super();
this.name = name;
this.age = age;
GPA = gPA;
}
#Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", GPA=" + GPA + "]";
}
}
StudentSorter.java
import java.util.Comparator;
public class StudentSorter implements Comparator<Student> {
#Override
public int compare(Student o1, Student o2) {
if(o1.getGPA() < o2.getGPA()) return 1;
if(o1.getGPA() > o2.getGPA()) return -1;
else return 0;
}
}
Tester.java
public class Tester {
public static void main(String[] args) {
Student s1 = new Student("A",14,7.9);
Student s2 = new Student("B",17,8.2);
Student s3 = new Student("C",20,7.0);
Student s4 = new Student("D",15,6.9);
Student s5 = new Student("E",14,9.1);
List<Student> list = new ArrayList<>();
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
StudentSorter ss = new StudentSorter();
Collections.sort(list, ss);
System.out.println(list.toString());
}
}

Display multiple String items 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;
}
}

Adding Items to my inventory in Java

I am making a text-based game on JavaFX, and after I hit a tree, I want to get Oak logs.
I have already built my inventory, and I have put default items in it such as Water, Bread, etc.
I am trying to add my Oak Logs to my inventory, but nothing is working.
Here is a part of my code:
Item ItemList[] = {new Bread(), new OakLog()};
Optional<ButtonType> result = alert.showAndWait();
if(result.get() == buttonTypeOak) {
woodcuttingXP = woodcuttingXP + oakXP;
dialogue.appendText("You swing at an Oak tree. + " + oakXP + "XP.\n");
dialogue.appendText("You gathered 1 log.\n");
mainCharacter.getInventory().add(new OakLog());
}
Here is my Item Class:
package game;
public class Item {
private String name;
private int weight;
private int quantity;
private int value;
private String description;
public Item(String name, int value, String description) {
this.name = name;
this.value = value;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String toString() {
return getName();
}
}
And finally, here is my Character class:
package game;
import java.util.ArrayList;
import beverages.Water;
import items.OakLog;
import rawFood.Bread;
public class Character {
private String name;
private int hydrationLevel;
private int healthLevel;
private int hungerLevel;
private int woodcuttingLevel;
public int getWoodcuttingLevel() {
return woodcuttingLevel;
}
public void setWoodcuttingLevel(int woodcuttingLevel) {
this.woodcuttingLevel = woodcuttingLevel;
}
public int getHungerLevel() {
return hungerLevel;
}
public void setHungerLevel(int hungerLevel) {
this.hungerLevel = hungerLevel;
}
private ArrayList<Item> inventory = new ArrayList<Item>();
public ArrayList<Item> getInventory() {
return inventory;
}
public void setInventory(ArrayList<Item> inventory) {
this.inventory = inventory;
}
//creates a person with two basic items
public Character(String name){
this.name = name;
this.hydrationLevel = 100;
this.healthLevel = 100;
this.hungerLevel = 100;
this.woodcuttingLevel = 1;
addToInventory (new Bread());
addToInventory (new OakLog());
addToInventory (new Water());
}
//GETTERS AND SETTERS
public String getName() {
return name;
}
public int getHydrationLevel() {
return hydrationLevel;
}
public void setHydrationLevel(int hydrationLevel) {
this.hydrationLevel = hydrationLevel;
}
public int getHealthLevel() {
return healthLevel;
}
public void setHealthLevel(int healthLevel) {
this.healthLevel = healthLevel;
}
//END GETTERS AND SETTERS
/*Method Name: eat()
*Method Inputs: a piece of food
*Method Purpose: Will allow the user to eat food
*/
public Item getItemFromInventory(int index){
Item item = inventory.get(index);
return item;
}
public void addToInventory(Item item){
if(inventory.contains(item)){
item.setQuantity(item.getQuantity()+1);
}
else{
item.setQuantity(1);
inventory.add(item);
}
}
public String toString(){
return "Character Stats:\nName:" + getName() + "\nHydration: " + getHydrationLevel() + "\nHealth: " + getHealthLevel() + "\nWoodcutting: " + getWoodcuttingLevel();
}
}
In your code, you have:
if(inventory.contains(item)){
item.setQuantity(item.getQuantity()+1);
}
This just updates the quantity of the local variable item in the method, not the item in the inventory.

Java List Sorting [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
public class Lot implements Listable {
int EmpID;
String Ename;
double Sal;
public Lot(int id,String ename, double sal) {
this.EmpID = id;
this.Ename = ename;
this.Sal = sal;
}
public int getEmpID() {
return EmpID;
}
public String getEname() {
return Ename;
}
public double getSal() {
return Sal;
}
public String toString() {
return "ID - " + EmpID + "\n" + "Name - " + Ename + "\n" + "Salary - " + Sal;
}
#Override
public int compareTo(Listable otherList) {
Lot other = (Lot)otherList;
return (this.EmpID - other.EmpID);
}
}
Main Class :
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SortTest {
public static void main(String[] args) {
List list = new ArrayList();
list.add(new Lot(4, "aaa", 12000));
list.add(new Lot(3, "bbb", 1000));
list.add(new Lot(1, "ccc", 8000));
list.add(new Lot(2, "ddd", 2500));
Collections.sort(list); //ERROR
}
}
This gives an Error 'Lot cannot be cast to java.lang.Comparable'
What is the mistake...
Create a Class which implements Comparable interface like below :
public class Lot implements Comparable<Lot> {
private int lotNumber;
private String firstName;
private String lastName;
private BigDecimal price;
private Long squareFeet;
private int numberofBedRooms;
public int getLotNumber() {
return lotNumber;
}
public void setLotNumber(int lotNumber) {
this.lotNumber = lotNumber;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Long getSquareFeet() {
return squareFeet;
}
public void setSquareFeet(Long squareFeet) {
this.squareFeet = squareFeet;
}
public int getNumberofBedRooms() {
return numberofBedRooms;
}
public void setNumberofBedRooms(int numberofBedRooms) {
this.numberofBedRooms = numberofBedRooms;
}
#Override
public int compareTo(Lot lot) {
return this.lotNumber - lot.lotNumber;
}
}
After this create a List of this object with all the values populated and use Collections.sort(---).
I just add the instruction not the code implementation -
Create a class Lot with lotNum and other property. Implement the interface comparable interface for this class.
Add all these lot to collection like ArrayList - lotList
Now call the Collections.sort()
Hope it will help.
Thanks a lot.
An example of how you can do :
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TestJava {
public static void main(String[] args) throws java.text.ParseException {
List<Lot> lots = new ArrayList<Lot>();
lots.add(new Lot(2, "bbb", "ccc", "bbb", "sss", "ccc"));
lots.add(new Lot(4, "bbb", "ccc", "bbb", "sss", "ccc"));
lots.add(new Lot(3, "bbb", "ccc", "bbb", "sss", "ccc"));
lots.add(new Lot(1, "bbb", "ccc", "bbb", "sss", "ccc"));
Collections.sort(lots);
}
}
Create Lot class :
class Lot implements Comparable<Lot> {
public int lotNumber;
public String firstName;
public String lastName;
public String price;
public String squareFeet;
public String noOfBedRooms;
public Lot(int lotNumber, String firstName, String lastName, String price, String squareFeet, String noOfBedRooms) {
this.lotNumber = lotNumber;
this.firstName = firstName;
this.lastName = lastName;
this.price = price;
this.squareFeet = squareFeet;
this.noOfBedRooms = noOfBedRooms;
}
public int getLotNumber() {
return lotNumber;
}
public void setLotNumber(int lotNumber) {
this.lotNumber = lotNumber;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getSquareFeet() {
return squareFeet;
}
public void setSquareFeet(String squareFeet) {
this.squareFeet = squareFeet;
}
public String getNoOfBedRooms() {
return noOfBedRooms;
}
public void setNoOfBedRooms(String noOfBedRooms) {
this.noOfBedRooms = noOfBedRooms;
}
#Override
public int compareTo(Lot lot) {
return this.getLotNumber() - lot.getLotNumber();
}
}
Change type of the attributes as you wish.
After the post I realized this is same answer as #Aalekh :)
there is a lot of sorting method that you can implement such as heap sort and bubble sort then you can implement substring in order to reorganize your data :d
for example you can user heap sort , `public static void BubbleSort( int [ ] num )
{
int j;
boolean flag = true; // set flag to true to begin first pass
int temp; //holding variable
while ( flag )
{
flag= false; //set flag to false awaiting a possible swap
for( j=0; j < num.length -1; j++ )
{
if ( num[ j ] < num[j+1] ) // change to > for ascending sort
{
temp = num[ j ]; //swap elements
num[ j ] = num[ j+1 ];
num[ j+1 ] = temp;
flag = true; //shows a swap occurred
}
}
}
}
`
it will take parameters (numbers) sort them and then you use substring ;)

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