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 9 years ago.
Improve this question
I am making a program where I have a class called GroceryItem, Another called GroceryList, and the third is main method which will run the program.
I have done alot in this program, but I am stuck now. Please have a look on my code and help me.
GroceryItem Class:
public class GroceryItem {
private String name;
private double pricePerUnit;
private int quantity;
public GroceryItem(int quantity, String name, double pricePerUnit) {
this.name = name;
this.pricePerUnit = pricePerUnit;
this.quantity = quantity;
}
public double getCost() {
return (this.quantity * this.pricePerUnit);
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
GroceryList Class:
public class GroceryList {
private GroceryItem[] list = null;
int num;
public GroceryList() {
list = new GroceryItem[10];
this.num = 0;
}
// Constructs a new empty grocery list.
public void add(GroceryItem item) {
list.add(item);
}
// Adds the given item order to this list, if the list is not full (has
// fewer than 10 items).
public double getTotalCost() {
double totalcost = 0;
for(int i = 0; i < list.length; i++){
totalcost += getGroceryItemOrder(getCost());
}
return totalcost;
}
// Returns the total sum cost of all grocery item orders in this list.
}
Main Method:
public static void main(String[] args) {
GroceryList list = new GroceryList();
GroceryItem carrots = new GroceryItem(5,"Carrots", 0.40);
list.add(carrots);
GroceryItem apples = new GroceryItem( 4,"Apples", 0.15);
list.add(apples);
GroceryItem rice = new GroceryItem( 1,"Rice", 1.10);
list.add(rice);
GroceryItem tortillas = new GroceryItem(10,"Tortillas", .05);
list.add(tortillas);
GroceryItem strawberries = new GroceryItem(1,"Strawberries", 4.99);
list.add(strawberries);
GroceryItem chicken = new GroceryItem( 1,"Chicken", 5.99);
list.add(chicken);
GroceryItem lettuce = new GroceryItem( 1,"Lettuce", 0.99);
list.add(lettuce);
GroceryItem milk = new GroceryItem( 2,"Milk", 2.39);
list.add(milk);
GroceryItem yogurt = new GroceryItem( 3,"Yogurt", 0.60);
list.add(yogurt);
GroceryItem chocolate = new GroceryItem(1,"Chocolate", 3.99);
list.add(chocolate);
}
}
You are trying to use the method add to add things to an array.
You should either use an ArrayList or similar data structure, or add items using an index:
list[ index++ ] = item
The reason is that simple arrays don't have an add method. ArrayList, and several other collection classes, do.
Also, in your original code, you have the line:
totalcost += getGroceryItemOrder(getCost());
There is no method getGroceryItemOrder(...) defined in this code. And, in this form, it will call getCost() on the GroceryItemList class. GroceryItemList has no such method, so you get an error.
You want to call getCost() on the current list item, so the line you need is:
totalcost += list[i].getCost();
Use this to add your Grocery element.
GroceryList class
public class GroceryList {
List<GroceryItem> list = null;
int num;
public GroceryList() {
list = new ArrayList<GroceryItem>();
this.num = 0;
}
// Constructs a new empty grocery list.
public void add(GroceryItem item) {
list.add(item);
System.out.println("Added Grocery :::: >>>> NAME:" +item.getName()+ " ::::: PRICE PER UNIT: "+item.getPricePerUnit()+" :::::: QUANTITY: "+item.getQuantity()+" ::::: FINALCOST: "+(item.getQuantity()*item.getPricePerUnit()) );}
// Adds the given item order to this list, if the list is not full (has
// fewer than 10 items).
public double getTotalCost() {
double totalcost = 0;
for(int i = 0; i < list.size(); i++){
totalcost += list.get(i).getCost();
}
return totalcost;
}
// Returns the total sum cost of all grocery item orders in this list.
}
/// Add this function as toString class
#Override
public String toString() {
return "GroceryList [list=" + list + ", num=" + num + "]";
}
// add a function for finding cost per item like this
public HashMap<String,Double> getCostPerItem(int i) {
HashMap<String, Double> itemPriceName= new HashMap<String, Double>();
itemPriceName.put(list.get(i).getName(),
(list.get(i).getPricePerUnit()*list.get(i).getQuantity()));
return itemPriceName;
}
// IN main function you can call above specified function
for(int i=0;i<list.list.size();i++) {
System.out.println("Cost Per Item "+list.getCostPerItem(i));
}
Related
I have two classes here:
public class Invoice {
ArrayList<Double> ItemPrices= new ArrayList<Double>();
ArrayList<Boolean> ItemIsPet = new ArrayList<Boolean>();
ArrayList<Integer> ItemQuantitys = new ArrayList<Integer>();
public void add(Item anItem){
}
public static void main(String args[]){
int counter = 0;
boolean pet;
Scanner s = new Scanner(System.in);
do {
System.out.println();
System.out.print("Item " + counter+1 + ":");
System.out.println();
System.out.print("Please enter the item's price: ");
double inputprice = s.nextDouble();
System.out.println();
System.out.print("Is this item a pet? (Y/N): ");
String inputIsPet = s.next();
if (inputIsPet.equals('Y')){
pet = true;
}
else {
pet = false;
}
System.out.println();
System.out.print("What is the quantity of this item?: ");
int inputquantity = s.nextInt();
Item newItem = new Item(inputprice, pet, inputquantity);
counter += 1;
} while (true);
}
}
And here is the second class:
public class Item {
Invoice Inv = new Invoice();
public Item(double price, boolean isPet, int quantity){
}
}
My question is for this line right here:
Item newItem = new Item(inputprice, pet, inputquantity);
So I have those 3 necessary arguments from the user input so that I can make a new object newItem of type item, but my question is once I have object newItem, how can I access those inputted arguments? My assignment is forcing me to implement this particular "add" method:
public void add(Item anItem)
Basically, the way I want to use this method is to take the inputted arguments from here:
Item newItem = new Item(inputprice, pet, inputquantity);
and have the "add" method access them, and from there put them into these arrays:
ArrayList<Double> ItemPrices= new ArrayList<Double>();
ArrayList<Boolean> ItemIsPet = new ArrayList<Boolean>();
ArrayList<Integer> ItemQuantitys = new ArrayList<Integer>();
But how do I access the parts of the object newItem? Do I have to modify my constructor in some way?
Do I have to modify my constructor in some way?
Yes, you need to save incoming values into instance fields.
public class Item {
private final double price;
private final boolean isPet;
private final int quantity;
public Item(double price, boolean isPet, int quantity) {
this.price = price;
this.isPet = isPet;
this.quantity = quantity;
}
}
How can I access those inputted arguments?
Then you can write a getter for each field you want to access to.
public double getPrice() {
return price;
}
How do I access the parts of the object newItem?
Now you can.
double price = newItem.getPrice();
So I need to grab the itemPrice part of the index and add them all together, but i'm not sure how to go about accessing that. Can I somehow use my getCost method from the GroceryItemOrder class and continuously add it to the totalCost in the GroceryList class, or do I need to access the itemPrice and quantity part of each stored object.
public class GroceryList {
public GroceryItemOrder[] groceryList = new GroceryItemOrder[0];
public int manyItems;
public GroceryList() {
final int INITIAL_CAPACITY = 10;
groceryList = new GroceryItemOrder[INITIAL_CAPACITY];
manyItems = 0;
}
//Constructs a new empty grocery list array
public GroceryList(int numItem) {
if (numItem < 0)
throw new IllegalArgumentException
("The amount of items you wanted to add your grocery list is negative: " + numItem);
groceryList = new GroceryItemOrder[numItem];
manyItems = 0;
}
public void add(GroceryItemOrder item) {
if (manyItems <= 10) {
groceryList[manyItems] = item;
}
manyItems++;
}
//
// #return the total sum list of all grocery items in the list
public double getTotalCost() {
double totalCost = 0;
for (int i = 0; i < groceryList.length; i++ ) {
//THIS PART
}
return totalCost;
}
}
And this is GroceryItemOrder
public class GroceryItemOrder {
public String itemName;
public int itemQuantity;
public double itemPrice;
public GroceryItemOrder(String name, int quantity, double pricePerUnit) {
itemName = name;
itemQuantity = quantity;
itemPrice = pricePerUnit;
}
public double getcost() {
return (itemPrice*itemQuantity);
}
public void setQuantity(int quantity) {
itemQuantity = quantity;
}
public String toString() {
return (itemName + " " + itemQuantity);
}
}
Thanks for all the replies! I got it working and understand what's going on here now.
You first need to access an instance of GroceryItemOrder in the array and from there then access its itemPrice field like so,
groceryList[0].itemPrice
would give you the itemPrice of the first groceryListOrder in the groceryList array. If you want to use a method to do this instead, then add a getItemPrice method in your groceryListOrder class,
public getItemPrice() {
return itemPrice;
}
Then you can access each groceryListOrder's itemPrice in the array like so,
groceryList[0].getItemPrice()
would do the same as groceryList[0].itemPrice. If you wanna get the total cost of all the objects in the groceryList array, then use a loop to add all the itemPrice fields multiplied by the itemQuantity field (since it's the totalcost of each object being summed together) by using your getcost method,
double totalCost = 0;
for (int i = 0; i < groceryList.length; i++) {
totalCost += groceryList[i].getcost();
}
First of all you should encapsulate all fields ofGroceryItemOrder class, so all the fields should be private member of the class and then use their setter/getter methods to access them in GroceryList.
Secondly, this implementation has a bug. The second constructor gets numItem as input and initialize array size accordingly. But, add method does not look at the real size and that might cause invalid array index exception. Consider this code:
GroceryList list = new GroceryList(2);
for (int i=0; i<10; i++)
list.add(new GroceryItemOrder("grocery", 5, 10));
The exception will be occurred when i=2
This works for me, you would need to set static GroceryItemOrder[] groceryList = new GroceryItemOrder[0]; as well:
//
// #return the total sum list of all grocery items in the list
public static double getTotalCost() {
double totalCost = 0;
for (int i = 0; i < groceryList.length; i++ )
{
totalCost += groceryList[i].getcost();
}
return totalCost;
}
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 8 years ago.
Improve this question
I was assigned an assignment that creates two classes (UsedCars and TestCars) using object oriented programming.
The assignment has 6 private attributes, 2 constructors (with and without arguments), and 10 accessors and mutators. Then a way to display the results.
The second class will test UsedCars with a Corolla and a Taurus.
The last instruction is what I'm having trouble with:
"Finally create an array of 100 used cars called Cars. Initialize them with a FOR loop to the defaults created in the original constructor and then display Cars[53]."
Here's what I have:
public class UsedCars {
private String make = "No Make";
private String model = "No Model";
private int year = 0;
private int miles = 0;
private double price = 0;
private int numberInLot = 0;
UsedCars() {numberInLot++;}
UsedCars(String newMake, String newModel, int newYear, int newMiles,
double newPrice) {
make = newMake;
model = newModel;
year = newYear;
miles = newMiles;
price = newPrice;
numberInLot++;
}//used cars
public String getMake() {
return make;
}//get make
public void setMake(String newMake) {
make = newMake;
}//set make
public String getModel() {
return model;
}//get model
public void setModel(String newModel) {
model = newModel;
}//set model
public int getYear() {
return year;
}//get year
public void setYear(int newYear) {
year = newYear;
}//set year
public int getMiles() {
return miles;
}//get miles
public void setMiles(int newMiles) {
miles = newMiles;
}//set miles
public double getPrice() {
return price;
}//get price
public void setPrice(double newPrice) {
price = newPrice;
}//set price
public void display() {
System.out.println("Make: " + make);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
System.out.println("Miles: " + miles);
System.out.println("Price: $" + price);
}//display
public int getNumberInLot(int numberInLot) {
return numberInLot;
}
public void displayNumberOfCars() {
System.out.println("Number of cars on the lot: " + numberInLot);
}//display number of cars
}
And here's the test:
public class TestCars {
public static void main (String[] args) {
UsedCars Car1 = new UsedCars();
Car1.setMake("Toyota");
Car1.setModel("Corolla");
Car1.setYear(1999);
Car1.setMiles(128000);
Car1.setPrice(5000.0);
Car1.display();
System.out.println();
UsedCars Car2 = new UsedCars();
Car2.setMake("Ford");
Car2.setModel("Taurus");
Car2.setYear(1992);
Car2.setMiles(212000);
Car2.setPrice(2000.0);
Car2.display();
System.out.println();
Car1.displayNumberOfCars();
System.out.println();
}//main
UsedCars[] Cars = new UsedCars[100];
for (int i = 0; i < Cars.getNumberInLot; i++) {
System.out.println(Cars[i].)
}
public static int carLot(UsedCars[] Cars) {
}//car lot
}
I would appreciate any help you guys can give me.
You are not initializing the array of objects you are creating.
It says :
"Finally create an array of 100 used cars called Cars. Initialize them with a FOR loop to the defaults created in the original constructor and then display Cars[53]."
for(int i=0; i<100; i++)
{
Cars[i] = UsedCars(); // I dont know which constructor to use here for DEFAULTS
}
Then you can print all values by
Cars[53].display();
And do all of these things inside main function of class TestCars
Having problems linking this program to this class. The program takes in a set of String + double arrays and goes through a series of sorts to yield a result. Our instructions are to sort then by name and sort then by price.
Main problem is that the Strings are displaying as hexadecimal eg(Item#4fjipe) etc.
Second problem is my sorts. I just have no idea how to make them work. Please help if at all possible. I will include both the class and the program. Bear in mind they are 2 different .java working together. I'm a beginner, by the way.
public class Item
{
private String itemName; // hold the name of the item
private double itemPrice; // hold the price of the item
public Item(String s, double p) // Constructor
{
itemName = s;
itemPrice = p;
}//end constructor
public void setName(String n)
{//method to set the item name
itemName = n;
}//end method
public String getName()
{//method to get the item name
return itemName;
}//end method
public double setPrice(double p1)
{//method to set the price of the item
itemPrice = p1;
return itemPrice;
}//end method
public double getPrice()
{//method to get the price of the item
return itemPrice;
}//end method
}//end class
AND NOW THE OTHER BEGINS. THIS ONE IS STILL A HOT MESS.
import javax.swing.*;
import java.util.Arrays;
public class CoffeeDriver
{
public static void main (String[] args)
{
Item[] itemArray = new Item[5]; // Array of type Item declaration
boolean loopControl = false; //variable for control of our loop
while (!loopControl)
{
itemArray[0] = new Item("Coffee", 1.00);
itemArray[1] = new Item("Water", 2.00);
itemArray[2] = new Item("Milk", 1.50);
itemArray[3] = new Item("Bagel",1.25);
itemArray[4] = new Item("Donut", 0.75);
String input = JOptionPane.showInputDialog(null, "Welcome to Wings Coffee Shop. We have a great list items on our menu. \nWould you like to see these items sorted by name of by price? (n/p):");
if(input.equals("n"))
{
sortName(itemArray);
JOptionPane.showMessageDialog(null, itemArray);
}//end if
else if(input.equals("p"))
{
sortPrice(itemArray);
JOptionPane.showMessageDialog(null, itemArray);
}
else
{
loopControl = true;
}
}//end while
}//end main
public static void sortName(Item[] itemArray)
{
int n = itemArray.length;
Item temp = new Item("",0);
for (int i =0; i < n; i++)
{
for(int j =1; j<(n-1); j++)
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
if(itemArray[j+1] == itemArray[j])
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
itemArray[j+1].setPrice(itemArray[j].getPrice());
itemArray[j+1].setName(itemArray[j].getName());
itemArray[j].setPrice(temp.getPrice());
itemArray[j].setName(temp.getName());
temp = itemArray[j+1];
itemArray[j+1] = itemArray[j];
itemArray[j] = temp;
JOptionPane.showMessageDialog(null, itemArray);
}//end if
}//end inner for
}//end outer for
}//end sortName
public static void sortPrice(Item[] itemArray)
{
int n = itemArray.length;
Item temp = new Item("",0);
for (int i =0; i < n; i++)
{
for(int j =1; j<(n-1); j++)
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
if(itemArray[j+1] == itemArray[j])
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
itemArray[j+1].setPrice(itemArray[j].getPrice());
itemArray[j+1].setName(itemArray[j].getName());
itemArray[j].setPrice(temp.getPrice());
itemArray[j].setName(temp.getName());
temp = itemArray[j+1];
itemArray[j+1] = itemArray[j];
itemArray[j] = temp;
JOptionPane.showMessageDialog(null, itemArray);
}//end if
}//end inner for
}//end outer for
}//end sortPrice
}//end class
You need to override the toString method in your Item class. You could use:
#Override
public String toString() {
return "Item [itemName=" + itemName + ", itemPrice=" + itemPrice + "]";
}
As you need to have 2 separate methods to sort by name and by price, you could use a custom comparator for both cases, using the appropriate field to compare against. Have a look at Arrays.sort() for doing the actual sorting.
'Item#4fjipe' is the object reference as provided by the default implementation of Object.toString() - read the API for reference.
A hexadecmial literal in Java start swith 0x, e.g. 0x10.
For your specific problem, you have a data object that you wish to sort in 2 different ways. Read the API documentation for Comparator and Comparable. Then check the Collections API to see which collections might offer you sorting.
I have the following code. When I try to compile it, it gives me the following error:
The method sort(List<T>, Comparator<? super T>) in the type Collections is not
applicable for the arguments (Software[], new Comparator(){})
The type new Comparator(){} must implement the inherited abstract method
Comparator.compare(Object, Object)
Code
import java.text.DecimalFormat; // For proper currency
import java.util.Comparator;
import java.util.Collections;
public class Software
{
// Declare variables
String SoftwareTitle; // SoftwareTitle
int SoftwareStock; // Software totals
double SoftwarePrice; // Software Price
int SoftwareNum; // Software Product ID
double CalculateInventory; // To add inventory
double SoftwareValue; // Software Total value
double value; // Complete inventory total
Software( String softtitle, int softstock, double softprice, int softitemnum )
{
// Create object constructor
SoftwareTitle = softtitle;
SoftwareStock = softstock;
SoftwarePrice = softprice;
SoftwareNum = softitemnum;
}
// Set Software Title
public void setSoftwareTitle( String softtitle )
{
SoftwareTitle = softtitle;
}
// Return Software Title
public String getSoftwareTitle()
{
return SoftwareTitle;
}
// Set software inventory
public void setSoftwareStock( int softstock)
{
SoftwareStock = softstock;
}
// Return software inventory
public int getSoftwareStock()
{
return SoftwareStock;
}
// Set software price
public void setSoftwarePrice( double softprice )
{
SoftwarePrice = softprice;
}
// Return software price
public double getSoftwarePrice()
{
return SoftwarePrice;
}
// Set item number
public void setSoftwareNum( int softitemnum )
{
SoftwareNum = softitemnum;
} //
//return software item number
public int getSoftwareNum()
{
return SoftwareNum;
} //
// calculate inventory value
public double Softwarevalue()
{
return SoftwarePrice * SoftwareStock;
}
public void setCalculateInventory (double value){
this.CalculateInventory = value;
}
public double getCalculateInventory(){
double value = 0;
for(int i = 0; i < 3; i++){
value = Softwarevalue();
}
return value;
}
}//end method value
//
import java.text.DecimalFormat; // For proper currency
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
public class Inventory {
public static void main( String args[] )
{
// Start array of software titles
Software[] aSoftware = new Software[4];
aSoftware[0]= new Software("Command and Conquer ", 6, 29.99, 10122);
aSoftware[1]= new Software("Alice in Wonderland", 1, 10.99,10233);
aSoftware[2]= new Software("Doom", 1, 10.99, 10344);
aSoftware[3]= new Software("Walking Dead", 6, 9.99, 10455);
//Set currency format
DecimalFormat money = new DecimalFormat("$0.00");
// Sort in order of Software Name
Collections.sort(aSoftware, new Comparator() {
public int compare(Software s1, Software s2) {
return s1.getSoftwareTitle().compareTo(s2.getSoftwareTitle());
}
});
// Display software title, number of units, cost, item number and total inventory
for (int i = 0; i < aSoftware.length; i++){
System.out.println("Software Title is "+ aSoftware[i].getSoftwareTitle() );
System.out.println("The number of units in stock is "+ aSoftware[i].getSoftwareStock() );
System.out.println("The price of the Software Title is "+ (money.format(aSoftware[i].getSoftwarePrice() )));
System.out.println( "The item number is "+ aSoftware[i].getSoftwareNum());
System.out.println( "The value of the Software Inventory is "+ (money.format(aSoftware[i].Softwarevalue() )));
System.out.println();
}
//output total inventory value
double total = 0.0;
for (int i = 0; i < 3; i++){
total += aSoftware[i].getCalculateInventory();
}
System.out.printf("Total Value of Software Inventory is: \t$%.2f\n", total);
//end output total inventory value
}
}
//
//end
How do I get the software titles (an array) to display in alphabetical order using the Comparator?
You've got two problems:
1) You're using Collections.sort (which takes a List<E>), but trying to sort an array. Use Arrays.sort instead.
2) You need to specify that you're implementing Comparator<Software>, not just the raw Comparator type.
So basically, this works:
Arrays.sort(aSoftware, new Comparator<Software>() {
public int compare(Software s1, Software s2) {
return s1.getSoftwareTitle().compareTo(s2.getSoftwareTitle());
}
});
Firstly: to sort an array, such as Software[], you need to use java.util.Arrays.sort rather than java.util.Collections.sort.
Secondly: since your Comparator is specifically for Software instances, you should write new Comparator<Software>() rather than merely new Comparator(). (The latter is actually bad code even when it does work.)
You can't sort on array when using Collections.sort. Collections.sort accepts only List. user Arrays.sort rather than Collection.sort.
Because you are trying to use array of object use below:
Arrays.sort(aSoftware);
and your software class should implements implements Comparable and override its compareTo method:
#Override
public int compareTo(Software o) {
return this.getSoftwareTitle().compareTo(o.getSoftwareTitle());
}
I have made correction to your class as below:
public class Software implements Comparable<Software>{
// Declare variables
String SoftwareTitle; // SoftwareTitle
int SoftwareStock; // Software totals
double SoftwarePrice; // Software Price
int SoftwareNum; // Software Product ID
double CalculateInventory; // To add inventory
double SoftwareValue; // Software Total value
double value; // Complete inventory total
Software(){
}
Software(String softtitle, int softstock, double softprice, int softitemnum)
{
// Create object constructor
SoftwareTitle = softtitle;
SoftwareStock = softstock;
SoftwarePrice = softprice;
SoftwareNum = softitemnum;
}
// Set Software Title
public void setSoftwareTitle(String softtitle) {
SoftwareTitle = softtitle;
}
// Return Software Title
public String getSoftwareTitle() {
return SoftwareTitle;
}
// Set software inventory
public void setSoftwareStock(int softstock) {
SoftwareStock = softstock;
}
// Return software inventory
public int getSoftwareStock() {
return SoftwareStock;
}
// Set software price
public void setSoftwarePrice(double softprice) {
SoftwarePrice = softprice;
}
// Return software price
public double getSoftwarePrice() {
return SoftwarePrice;
}
// Set item number
public void setSoftwareNum(int softitemnum) {
SoftwareNum = softitemnum;
} //
// return software item number
public int getSoftwareNum() {
return SoftwareNum;
} //
// calculate inventory value
public double Softwarevalue() {
return SoftwarePrice * SoftwareStock;
}
public void setCalculateInventory(double value) {
this.CalculateInventory = value;
}
public double getCalculateInventory() {
double value = 0;
for (int i = 0; i < 3; i++) {
value = Softwarevalue();
}
return value;
}
#Override
public int compareTo(Software o) {
return this.getSoftwareTitle().compareTo(o.getSoftwareTitle());
}
}// end method value
Your Inventory class:
public class Inventory {
public static void main(String args[])
{
// Start array of software titles
Software[] aSoftware = new Software[4];
aSoftware[0] = new Software("Command and Conquer ", 6, 29.99, 10122);
aSoftware[1] = new Software("Alice in Wonderland", 1, 10.99, 10233);
aSoftware[2] = new Software("Doom", 1, 10.99, 10344);
aSoftware[3] = new Software("Walking Dead", 6, 9.99, 10455);
// Set currency format
DecimalFormat money = new DecimalFormat("$0.00");
Arrays.sort(aSoftware);
// Display software title, number of units, cost, item number and total
// inventory
for (int i = 0; i < aSoftware.length; i++) {
System.out.println("Software Title is "
+ aSoftware[i].getSoftwareTitle());
System.out.println("The number of units in stock is "
+ aSoftware[i].getSoftwareStock());
System.out.println("The price of the Software Title is "
+ (money.format(aSoftware[i].getSoftwarePrice())));
System.out.println("The item number is "
+ aSoftware[i].getSoftwareNum());
System.out.println("The value of the Software Inventory is "
+ (money.format(aSoftware[i].Softwarevalue())));
System.out.println();
}
// output total inventory value
double total = 0.0;
for (int i = 0; i < 3; i++) {
total += aSoftware[i].getCalculateInventory();
}
System.out.printf("Total Value of Software Inventory is: \t$%.2f\n",
total);
// end output total inventory value
}
}
Below is final output in sorted order:
Software Title is Alice in Wonderland
The number of units in stock is 1
The price of the Software Title is $10.99
The item number is 10233
The value of the Software Inventory is $10.99
Software Title is Command and Conquer
The number of units in stock is 6
The price of the Software Title is $29.99
The item number is 10122
The value of the Software Inventory is $179.94
Software Title is Doom
The number of units in stock is 1
The price of the Software Title is $10.99
The item number is 10344
The value of the Software Inventory is $10.99
Software Title is Walking Dead
The number of units in stock is 6
The price of the Software Title is $9.99
The item number is 10455
The value of the Software Inventory is $59.94
Total Value of Software Inventory is: $201.92
You should make your "Software" class implement comparable and then overwrite the compare method to return a compare on the titles like you did outside your code. This will be a replacement for the comparator. Then all you need to to is call Arrays.sort.