Getters and Setters returning null - java

I'm trying to write a very simple program that produces an invoice for an item purchased.
I have a driver class with my setters and getters, and my object class which is supposed to call them. However, when I print out the invoice, it just produces null responses for everything.
Here is my driver class:
public class Invoice {
private String partNumber; //part number of item
private String description; //description of item
private int quantity; //quantity being purchased
private double itemPrice; //price of item
//constructor
public Invoice(String partNumber, String description, int quantity, double itemPrice) {
partNumber = partNumber;
description = description;
if (quantity < 0) {
quantity = 0;
}
if (itemPrice < 0.0) {
itemPrice = 0.0;
}
}
public void setPartNumber(String number) {
partNumber = number; //store the partNumber
}
public void setDescription(String description) {
description = description;//store the description
}
public void setQuantity(int quantity) {
quantity = quantity;//store the quantity
}
public void setItemPrice(double price) {
itemPrice = price;//store the itemPrice
}
public String getPartNumber() {
return partNumber;//retrieve the partNumber
}
public String getDescription() {
return description;//retrieve the description
}
public int getQuantity() {
return quantity;//retrieve the quantity
}
public double getItemPrice() {
return itemPrice;//retrieve the itemPrice
}
//get price for item purchased.
public double getInvoiceAmount(double amount) {
amount = itemPrice * quantity;
if (amount < 0) {
amount = 0.0;
}
return amount;
}
}
And here is my object class:
public class InvoiceTest {
public static void main(String[] args) {
Invoice invoice1 = new Invoice ("0001", "Hammer: used to hit nails.", 1, 10.0);
System.out.println("Item purchased: " + invoice1.getPartNumber() +
"\n Description: " + invoice1.getDescription() +
"\n Amount:" + invoice1.getQuantity() +
"\n price: " + invoice1.getQuantity());
System.out.println();
System.out.println("Total price: " + invoice1.getInvoiceAmount(amount));
}
}

You forgot to assign the variables to the fields in constructor. Use this keyword to refer to the class fields:
public Invoice(String partNumber, String description, int quantity, double itemPrice) {
//here's an example
//partNumber = partNumber
this.partNumber = partNumber;
//description = description;
this.description = description;
//similar for other assignments inside the constructor...
}
You must also do this in your setters as well:
public void setPartNumber(String partNumber) {
this.partNumber = partNumber; //store the partNumber
}

Your class's member fields are not being initialized as you intended, because of this:
public Invoice(String partNumber, String description, int quantity, double itemPrice)
{
partNumber = partNumber;
Here, partNumber refers to the function argument, not the member field. To set the member field, use this.partNumber = partNumber.

Your setters are not setting the values into the object instance, you need to make changes like below
public Invoice(String partNumber, String description, int quantity,
double itemPrice) {
this.partNumber = partNumber;
this.description = description;
this.quantity = quantity;
if (this.quantity < 0) {
this.quantity = 0;
}
this.itemPrice = itemPrice;
if (this.itemPrice < 0.0) {
this.itemPrice = 0.0;
}
}
public void setPartNumber(String number) {
this.partNumber = number; //store the partNumber
}
public void setDescription(String description) {
this.description = description;//store the description
}
public void setQuantity(int quantity) {
this.quantity = quantity;//store the quantity
}
public void setItemPrice(double price) {
this.itemPrice = price;//store the itemPrice
}

Related

Short Project: Electronics Inventory

I'm doing my short project that acts as a type of electronic store inventory. Here's the list of item's number, description, quantity, and price from the text file:
65321,Tablet,54,150.00
91524,Monitors,24,125.50
25013,Printers,30,65.75
32841,Router,67,90.15
53214,Modem,50,50.50
26442,Hard Drive,14,40.89
30224,Power Supplies,44,125.44
41557,CPU,39,149.54
71561,Headphones,40,75.24
This is what I've done so far:
InventoryCalculate.java
ArrayList<BookItem> inventory = new ArrayList<>();
BufferedReader inFile = new BufferedReader(new FileReader("C:\\Users\\Documents\\Data\\stock.txt"));
String line;
line = input.nextLine();
String[] tokens = line.split(",");
int itemNumber = Integer.parseInt(tokens[0]);
String description = tokens[1];
int quantity = Integer.parseInt(tokens[2]);
double unitCost = Double.parseDouble(tokens[3]);
System.out.println("Inventory Item");
System.out.println("Number Description Quantity Unit Price Value");
Inventorystock.java
public class InventoryItem {
private int itemNumber;
private String description;
private int quantity;
private double unitCost;
public InventoryItem(int itemNumber, String description, int quantity, double unitCost) {
this.itemNumber = itemNumber;
this.description = description;
this.quantity = quantity;
this.unitCost = unitCost;
}
public int getItemNumber() {
return itemNumber;
}
public void setItemNumber(int itemNumber) {
this.itemNumber = itemNumber;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getUnitCost() {
return unitCost;
}
public void setUnitCost(double unitCost) {
this.unitCost = unitCost;
} }
I'm having trouble figuring out how to get the total value of each item. Here what I need to see the result look like this
Expected output:
Number Description Quantity Unit Price Value
65321 Tablets 54 150.00 8,100.00
91524 Monitors 24 125.50 3,012.00
25013 Printers 30 65.75 1,972.50
32841 Routers 67 90.15 6,040.05
53214 Modems 50 50.50 2,525.00
26442 Hard Drives 14 40.89 572.46
30224 Power Supplies 44 125.44 5,519.36
41557 CPU 39 149.54 5,832.06
71561 Headphones 40 75.24 3,009.60
Create a method that takes the total quantity of the item, multiplies it by the unit cost and then returns the result. Add the following code to your InventoryItem class.
public double getTotalValueOfItem()
{
return unitCost * quantity;
}
Add another property in InventoryItem class as totalValue and add setter, getter methods with your logic. The best way to keep total value calculation in the method that you're displaying details.
public class InventoryItem {
private int itemNumber;
private String description;
private int quantity;
private double unitCost;
private double totalValue;
public InventoryItem(int itemNumber, String description, int quantity, double unitCost) {
this.itemNumber = itemNumber;
this.description = description;
this.quantity = quantity;
this.unitCost = unitCost;
}
public int getItemNumber() {
return itemNumber;
}
public void setItemNumber(int itemNumber) {
this.itemNumber = itemNumber;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getUnitCost() {
return unitCost;
}
public void setUnitCost(double unitCost) {
this.unitCost = unitCost;
}
public double getTotalValue() {
return totalValue;
}
public void setTotalValue(int quantity, double unitCost) {
this.totalValue = (double) quantity * unitCost;
}
}
You can add this method to print the item details
public void printDetails() {
System.out.println("Number\tDescription\tQuantity\tUnit Price\tValue");
List < InventoryItem > inventoryItemsList = new ArrayList < InventoryItem > ();
inventoryItemsList.add(new InventoryItem(1, "description 1", 2, 50.0));
inventoryItemsList.add(new InventoryItem(2, "description 2", 3, 40.0));
for (InventoryItem item: inventoryItemsList) {
System.out.println(item.itemNumber + "\t" + item.description + "\t" + item.quantity + "\t" + item.unitCost + "\t" + item.totalValue);
}
}
You can store the details of inventory items as a String or as a List as demonstrated in printDetails method. Hope this "printDetails" method solved your issue. If you really want to store item details as a string then you can store all item details into a string array.
Make sure to import required libraries and model classes in following way.
import java.util.List;
import java.util.ArrayList;
import <package>.InventoryItem;

Sum all double values of objects stored in ArrayList (Java)

I have an ArrayList that contains objects. Each of the object has 3 values: String name, double price, int quantity. How to write method that will sum all doubles of objects and print the result. And also if int quantity>1, price will be multiplied by quantity.
Code that i wrote so far:
Product class
public class Product {
private String name;
private double price;
private int quantity;
public Product(String name, double price, int quantity) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public static Product createProduct(String name, double price, int quantity){
return new Product(name, price, quantity);
}
}
Product list class
import java.util.ArrayList;
import java.util.List;
public class ProductList {
private String name;
List<Product> newList;
public ProductList(String name) {
this.name = name;
this.newList = new ArrayList<>();
}
public boolean addNewProduct(Product product) {
if (findProduct(product.getName()) >= 0) {
System.out.println("Product is already on the list");
return false;
}
newList.add(product);
return true;
}
public boolean removeProduct(Product product) {
if (findProduct(product.getName().toUpperCase()) < 0) {
System.out.println("Product not found");
return false;
}
newList.remove(product);
return true;
}
private int findProduct(String productName) {
for (int i = 0; i < newList.size(); i++) {
Product product = newList.get(i);
if (product.getName().equals(productName)) {
return i;
}
}
return -1;
}
public Product queryProduct(String name) {
int position = findProduct(name);
if (position >= 0) {
return this.newList.get(position);
}
return null;
}
public double sumProducts() {
double sum = 0;
for (int i = 0; i < newList.size(); i++) {
sum += newList.get(i).getPrice();
}
return sum;
}
/*public boolean listProducts(){};
public boolean updateProduct(){};
*/
}
Simulation class:
public class Simulation {
private static Scanner scanner = new Scanner(System.in);
private static ProductList myProductList = new ProductList("My list");
private static void addNewProduct() {
System.out.println("Enter new product name: ");
String name = scanner.nextLine();
System.out.println("Enter new product price: ");
double price = scanner.nextDouble();
System.out.println("Enter new product quantity");
int quantity = scanner.nextInt();
Product newProduct = Product.createProduct(name, price, quantity);
if (myProductList.addNewProduct(newProduct) == true) {
System.out.println("New product added: " + name + " | price: " + price + " | quantity: " + quantity);
}
}
private static void removeProduct() {
System.out.println("Enter product name: ");
String name = scanner.nextLine().toUpperCase();
Product existingProduct = myProductList.queryProduct(name);
if (existingProduct == null) {
System.out.println("No such product");
return;
}
if (myProductList.removeProduct(existingProduct)) {
System.out.println("Sucessfully deleted product: " + existingProduct.getName());
} else {
System.out.println("Error deleting");
}
}
private static void printActions() {
System.out.println("Avaiable actions");
System.out.println("press: ");
System.out.println("0 - to shut down\n" +
"1 - to add new product\n" +
"2 - to remove product\n" +
"3 - to sum all products");
}
private static void sumProducts(){
myProductList.sumProducts();
}
public static void main(String[] args) {
printActions();
boolean quit = false;
while (!quit)
try {
System.out.println("\nEnter action: ");
int action = scanner.nextInt();
scanner.nextLine();
switch ((action)) {
case 0:
System.out.println("\nShutting down...");
quit = true;
break;
case 1:
addNewProduct();
break;
case 2:
removeProduct();
break;
}
} catch (InputMismatchException e) {
System.out.println("Bad key pressed, only values form 0 to 2 accepted");
scanner.nextLine();
}
}
}
Thanks in advance
You can do it in one line using Java 8.
public double sumProducts() {
return newList.stream().mapToDouble(product -> product.getPrice() * product.getQuantity()).sum();
}
If you use double to store the price, you will get incorrect answers when you try to add and multiply the values. For example, 0.1 + 0.2 is NOT the same double as 0.3. If you want accurate arithmetic for decimal numbers, you should use the BigDecimal class in place of double. If you don't do that, I can guarantee that your program will sometimes give wrong answers.
So you need to change your Product class as follows.
public class Product {
private String name;
private BigDecimal price;
private int quantity;
public Product(String name, BigDecimal price, int quantity) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public BigDecimal getPrice() {
return price;
}
public static Product createProduct(String name, BigDecimal price, int quantity){
return new Product(name, price, quantity);
}
}
You will also need to make corresponding changes in the code that calls the methods of this class.
Once you've done that, you can use the methods of the BigDecimal class to do arithmetic. It might look something like this.
public BigDecimal calculateTotalPrice() {
BigDecimal total = BigDecimal.ZERO;
for (Product product : newList) {
BigDecimal linePrice = product.getPrice().multiply(new BigDecimal(product.getQuantity()));
total = total.add(linePrice);
}
return total;
}
the sum of each product was missing multiply by its quantity.
public double sumProducts() {
double sum = 0;
for (int i = 0; i < newList.size(); i++) {
Product product = newList.get(i);
sum += product.getPrice() * product.getQuantity();
}
return sum;
}

Creating a invoiceline class

Invoice Line class represent some line in the invoice that records the item sold and the quantity.An invoice line should include the following attributes: item Sold: this is an instance variable of type Item.
quantity: an integer that represents the number of units being purchased of this item.Include the following methods in your Invoice Line class: A constructor that takes the following four input parameters: item number, item description, item price, and quantity. The constructor then uses the input parameters to initialize the two instance variables to getters and setters methods for the two instance variable so get Line Total: a method to calculate and return the total price for this line (i.e., quantity * item’s price). to String method that returns a one-line description of the invoice line. The description should include item’s details, quantity purchased, and total cost of the line.
*** I am trying to get the other variables from a different class called item class to the invoiceline class, but I cannot seem to do it. So far I have this. Any Help!?
public class InvoiceLine {
//Instance Variables
private Item itemSold;
private int quantity;
// Constructors
public InvoiceLine(){}
public InvoiceLine(String itemSold, int quantity){
itemSold = new Item(itemSold);
this.quantity = quantity;
}
//Getters
public Item getItemSold(){
return itemSold;
}
public int getQuantity(){
return quantity;
}
//Setters
private void setItemSold(Item itemSold){
this.itemSold = itemSold;
}
private void setQuantity(int quantity){
this.quantity = quantity;
}
// Methods
public double getLineTotal(double total){
total = itemPrice * quantity;
return total;
}
public String toString(){
String invoiceLine = "";
invoiceLine = (itemSold + " brought "+ quantity + ", which the total cost is "+ total);
return invoiceLine;
}
}
Item Class:
public class Item {
//Instance Variables
private int itemNum;
private String itemDescription;
private double itemPrice;
//Constructors
public Item(){}
//Initialize the three variables
public Item(int itemN, String itemDesc, double itemPri){
this.itemNum = itemN;
this.itemDescription = itemDesc;
this.itemPrice = itemPri;
}
public Item(String itemDesc){
this.itemDescription = itemDesc;
this.itemNum = 0;
this.itemPrice = 0;
}
//Getters
public int getItemNum(){
return itemNum;
}
public String getItemDescription(){
return itemDescription;
}
public double getItemPrice(){
return itemPrice;
}
//Setters
private void setItemNum(int itemN){
itemNum = itemN;
}
private void setItemDescription(String itemDesc){
itemDescription = itemDesc;
}
private void setItemPrice(double itemPri){
itemPrice = itemPri;
}
// toString method output description of the item
public String toString(){
String itemDetail = "";
itemDetail = ("Item number is "+ itemNum + ", which is a "+ itemDescription + " and price is " + itemPrice);
return itemDetail;
}
}
Try to change itemSold = new Item(itemSold); to this.itemSold = new Item(itemSold);
In this case the parameter itemSold is shadowing the attribute itemSold, so to access the attribute you have to prefix it with this.

Point Of Sales - Stuck on arrays

Basically I have multiple classes and I'm trying to get an array of LineItem for each Item that a customer purchases. LineItem includes the UPC, Description, Price, Quantity, SubTotal and Discount which is all stored in a seperate class. I'm trying to get it that when you use the method addItemToSaleList it will add to the array. I need to use an array and not an array list, so I have to copy over the array to a temp array, and then recreate a new array adding to the number the array can store and then recopying it over. I'm stuck getting the array to generate. Below is the code I have
public class Product {
private double price;
private String description;
private String ProductCode;
private DiscountStrategy discoutStrategy;
public Product(double price, String description, String ProductCode, DiscountStrategy discoutStrategy) {
this.price = price;
this.description = description;
this.ProductCode = ProductCode;
this.discoutStrategy = discoutStrategy;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getProductCode() {
return ProductCode;
}
public void setProductCode(String ProductCode) {
this.ProductCode = ProductCode;
}
public DiscountStrategy getDiscountStrategy() {
return discoutStrategy;
}
public void setDiscoutStrategy(DiscountStrategy discoutStrategy) {
this.discoutStrategy = discoutStrategy;
}
}
public class LineItem {
private Product product;
private double quantity;
public LineItem(Product product, double quantity) {
this.product = product;
this.quantity = quantity;
}
//Calculates the Discount Amount whether or not it's a percentage or dollar
//off
public double getDiscountAmount () {
return product.getDiscountStrategy().getDiscount(product.getPrice(), quantity);
}
//Calculates the Subtotal, gets the quantity from the DiscountStrategy and then
//the price from the product
public double getSubTotal() {
return quantity * product.getPrice();
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public double getQuantity() {
return quantity;
}
public void setQuantity(double quantity) {
this.quantity = quantity;
}
public class Receipt {
private LineItem[] lineItem = new LineItem[0];
public Receipt(LineItem[] lineItem) {
this.lineItem = lineItem;
}
public void addProductToTotalSale(LineItem li) {
addItemToSaleList();
}
public void addItemToSaleList() {
LineItem[] tempItemList = new LineItem[lineItem.length + 1];
for (int i = 0; i < tempItemList.length; i++) {
tempItemList[i] = lineItem[i];
}
lineItem = new LineItem[tempItemList.length];
for (int j = 0; j < lineItem.length; j++) {
lineItem[j] = tempItemList[j];
}
}
public LineItem[] getLineItem() {
return lineItem;
}
I would remove addItemToSaleList() and implement addProductToTotalSale(LineItem) like so
public void addProductToTotalSale(LineItem li) {
// Allocate the memory.
LineItem[] tempLineItem = new LineItem[1 + lineItem.length];
// Copy the array.
if (lineItem.length > 0) {
System.arraycopy(lineItem, 0, tempLineItem, 0, lineItem.length);
}
// add the new item to the new slot.
tempLineItem[lineItem.length] = li;
// update the internal array reference.
lineItem = tempLineItem;
}
Next, you should protect your constructor from null;
public Receipt(LineItem[] lineItem) {
// Try and protect from bad calls, removes need to check for nulls in
// add (addProductToTotalSale) routine.
if (lineItem != null) {
this.lineItem = lineItem;
}
}
Because you provide a default 0 sized array your code appears to be safe to continue to include the default constructor. But, you might consider making your Receipt class immutable.
I'm not sure why you are making two new arrays. You only need one...
public void addProductToTotalSale(LineItem li) {
addItemToSaleList();
lineItem[lineItem.length-1] = li;
}
public void addItemToSaleList() {
LineItem[] tempItemList = new LineItem[lineItem.length + 1];
for (int i = 0; i < tempItemList.length; i++) {
tempItemList[i] = lineItem[i];
}
lineItem = tempItemList;
}

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