Sorting an array using Comparator - java

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.

Related

How do I access the itemPrice part of this array?

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

How to turn main method class to Junit test class?

I wrote a small project named Sales Taxes on Intellij IDEA. To run the program, I included a main method. Now I need to write JUnit tests for the project. I do not have much experience about writing test classes. How can I turn my main method to Junit test class?
Here is the project that I constructed:
Basic sales tax is applicable at a rate of 10% on all goods, except books, food, and medical products that are exempt.
Import duty is an additional sales tax applicable on all imported goods at a rate of 5%, with no exemptions.
When I purchase items I receive a receipt which lists the name of all the items and their price (including tax), finishing
with the total cost of the items, and the total amounts of sales taxes paid. The rounding rules for sales tax are that for
a tax rate of n%, a shelf price of p contains (np/100 rounded up to the nearest 0.05) amount of sales tax.
Write an application that prints out the receipt details for these shopping baskets...
Product.java
/*
Definition of Product.java class
Fundamental object for the project.
It keeps all features of the product.
At description of the product, description of the input line for output line.
typeOfProduct: 0:other 1:food 2:book 3: medical products
*/
public class Product{
private int typeOfProduct=0;
private boolean imported=false;
private double price=0;
private double priceWithTaxes=0;
private double taxes=0;
private int quantity=0;
private String description="";
public Product(int quantity, int typeOfProduct, boolean imported, double price, String description)
{
this.quantity=quantity;
this.typeOfProduct = typeOfProduct;
this.imported = imported;
this.price = price;
this.description = description;
}
public void setTypeOfProduct(int typeOfProduct)
{
this.typeOfProduct = typeOfProduct;
}
public int getTypeOfProduct()
{
return typeOfProduct;
}
public void setImported(boolean imported)
{
this.imported = imported;
}
public boolean getImported()
{
return imported;
}
public void setPrice(double price)
{
this.price = price;
}
public double getPrice()
{
return price;
}
public void setTaxes(double taxes)
{
this.taxes = taxes;
}
public double getTaxes()
{
return taxes;
}
public void setPriceWithTaxes(double priceWithTaxes)
{
this.priceWithTaxes = priceWithTaxes;
}
public double getPriceWithTaxes()
{
return priceWithTaxes;
}
public void setQuantity(int quantity)
{
this.quantity = quantity;
}
public int getQuantity()
{
return quantity;
}
public void setDescription(String description)
{
this.description = description;
}
public String getDescription()
{
return description;
}
}
TaxCalculator.java
/*
Definition of TaxCalculator.java class
At constructor a Product object is taken.
taxCalculate method; adds necessary taxes to price of product.
Tax rules:
1. if the product is imported, tax %5 of price
2. if the product is not food, book or medical goods, tax %10 of price
typeOfProduct: 0:food 1:book 2: medical products 3:other
*/
public class TaxCalculator {
private Product product=null;
public TaxCalculator(Product product)
{
this.product=product;
}
public void taxCalculate()
{
double price=product.getPrice();
double tax=0;
//check impoted or not
if(product.getImported())
{
tax+= price*5/100;
}
//check type of product
if(product.getTypeOfProduct()==3)
{
tax+= price/10;
}
product.setTaxes(Util.roundDouble(tax));
product.setPriceWithTaxes(Util.roundDouble(tax)+price);
}
}
Util.java
import java.text.DecimalFormat;
/*
Definition of Util.java class
It rounds and formats the price and taxes.
Round rules for sales taxes: rounded up to the nearest 0.05
Format: 0.00
*/
public class Util {
public static String round(double value)
{
double rounded = (double) Math.round(value * 100)/ 100;
DecimalFormat df=new DecimalFormat("0.00");
rounded = Double.valueOf(df.format(rounded));
return df.format(rounded).toString();
}
public static double roundDouble(double value)
{
double rounded = (double) Math.round(value * 20)/ 20;
if(rounded<value)
{
rounded = (double) Math.round((value+0.05) * 20)/ 20;
}
return rounded;
}
public static String roundTax(double value)
{
double rounded = (double) Math.round(value * 20)/ 20;
if(rounded<value)
{
rounded = (double) Math.round((value+0.05) * 20)/ 20;
}
DecimalFormat df=new DecimalFormat("0.00");
rounded = Double.valueOf(df.format(rounded));
return df.format(rounded).toString();
}
}
SalesManager.java
import java.util.ArrayList;
import java.util.StringTokenizer;
/*
Definition of SalesManager.java class
This class asks to taxes to TaxCalculator Class and creates Product objects.
*/
public class SalesManager {
private String [][] arTypeOfProduct = new String [][]{
{"CHOCOLATE", "CHOCOLATES", "BREAD", "BREADS", "WATER", "COLA", "EGG", "EGGS"},
{"BOOK", "BOOKS"},
{"PILL", "PILLS", "SYRUP", "SYRUPS"}
};
/*
* It takes all inputs as ArrayList, and returns output as ArrayList
* Difference between output and input arrayLists are Total price and Sales Takes.
*/
public ArrayList<String> inputs(ArrayList<String> items)
{
Product product=null;
double salesTaxes=0;
double total=0;
TaxCalculator tax=null;
ArrayList<String> output=new ArrayList<String>();
for(int i=0; i<items.size(); i++)
{
product= parse(items.get(i));
tax=new TaxCalculator(product);
tax.taxCalculate();
salesTaxes+=product.getTaxes();
total+=product.getPriceWithTaxes();
output.add(""+product.getDescription()+" "+Util.round(product.getPriceWithTaxes()));
}
output.add("Sales Taxes: "+Util.round(salesTaxes));
output.add("Total: "+Util.round(total));
return output;
}
/*
* The method takes all line and create product object.
* To create the object, it analyses all line.
* "1 chocolate bar at 0.85"
* First word is quantity
* Last word is price
* between those words, to analyse it checks all words
*/
public Product parse(String line)
{
Product product=null;
String productName="";
int typeOfProduct=0;
boolean imported=false;
double price=0;
int quantity=0;
String description="";
ArrayList<String> wordsOfInput = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(line, " ");
String tmpWord="";
while (st.hasMoreTokens())
{
tmpWord=st.nextToken();
wordsOfInput.add(tmpWord);
}
quantity=Integer.parseInt(wordsOfInput.get(0));
imported = searchImported(wordsOfInput);
typeOfProduct = searchTypeOfProduct(wordsOfInput);
price=Double.parseDouble(wordsOfInput.get(wordsOfInput.size()-1));
description=wordsOfInput.get(0);
for(int i=1; i<wordsOfInput.size()-2; i++)
{
description=description.concat(" ");
description=description.concat(wordsOfInput.get(i));
}
description=description.concat(":");
product=new Product(quantity, typeOfProduct, imported, price, description);
return product;
}
/*
* It checks all line to find "imported" word, and returns boolean as imported or not.
*/
public boolean searchImported(ArrayList<String> wordsOfInput)
{
boolean result =false;
for(int i=0; i<wordsOfInput.size(); i++)
{
if(wordsOfInput.get(i).equalsIgnoreCase("imported"))
{
return true;
}
}
return result;
}
//typeOfProduct: 0:food 1:book 2: medical goods 3:other
/*
* It checks all 2D array to find the typeOf product
* i=0 : Food
* i=1 : Book
* i=2 : Medical goods
*/
public int searchTypeOfProduct (ArrayList<String> line)
{
int result=3;
for(int k=1; k<line.size()-2; k++)
{
for(int i=0; i<arTypeOfProduct.length; i++)
{
for(int j=0; j<arTypeOfProduct[i].length; j++)
{
if(line.get(k).equalsIgnoreCase(arTypeOfProduct[i][j]))
{
return i;
}
}
}
}
return result;
}
}
SalesTaxes.java
import java.io.IOException;
import java.util.ArrayList;
public class SalesTaxes {
public static void main(String args[]) throws IOException
{
ArrayList<String> input = new ArrayList<String>();
ArrayList<String> output = new ArrayList<String>();
SalesManager sal = new SalesManager();
/*
* First input set
*/
System.out.println("First input Set");
System.out.println();
input = new ArrayList<String>();
input.add("1 book at 12.49");
input.add("1 music CD at 14.99");
input.add("1 chocolate bar at 0.85");
sal=new SalesManager();
output= sal.inputs(input);
for(int i=0; i<output.size(); i++)
{
System.out.println(output.get(i));
}
/*
* Second input set
*/
System.out.println();
System.out.println("Second input Set");
System.out.println();
input = new ArrayList<String>();
input.add("1 imported box of chocolates at 10.00");
input.add("1 imported bottle of perfume at 47.50");
sal=new SalesManager();
output= sal.inputs(input);
for(int i=0; i<output.size(); i++)
{
System.out.println(output.get(i));
}
/*
* Third input set
*/
System.out.println();
System.out.println("Third input Set");
System.out.println();
input = new ArrayList<String>();
input.add("1 imported bottle of perfume at 27.99");
input.add("1 bottle of perfume at 18.99");
input.add("1 packet of headache pills at 9.75");
input.add("1 box of imported chocolates at 11.25");
output= sal.inputs(input);
for(int i=0; i<output.size(); i++)
{
System.out.println(output.get(i));
}
}
}
I think that you can start with searching about how to write unit tests, maybe than you will not have this kind of question. The main point there is to test some piece of functionality. For example, in your case you should test taxCalculate method and check if in your product the tax was set correctly, probably you will need a getter for a product in this case.
Also, check this: how to write a unit test.
A "unit test" is for one class.
So I wouldn't start with the main method: that wouldn't give you "unit tests". That would give you an "integration test" (testing a bunch of your classes all at once).
So, for unit tests, I would start by writing a UtilTest class to test just your Util class. That has public methods that can easily be given different inputs and the results asserted. e.g. what do you get back if you give roundTax zero, or 21.0, etc.?

How can I get an ArrayList to print out information of different data types?

I have an assignment where I have to print US states by order of the highest to lowest percentage of eligible citizens enrolled in the Affordable Healthcare Act. I had to create an ArrayList and it holds two different types of data: two Strings and 3 doubles. I am very close to completion but I have been stumped at:
How do I print out the states line by line? I think I should use t/ to start a new line.
How do I print out the states in order of highest to lowest percentages?
Code so far.
import java.util.*;
import java.io.*;
import java.util.ArrayList;
// Calculates the percentage of citizens enrolled in the Affordable Healthcare Act
// Lists the states in order of highest percentage of enrolled citizens in the Affordable Healthcare Act
public class ACA {
public static void main( String[] args ) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in); // creates an object of the Scanner class
System.out.println("Enter filename"); // prompts the user for the name of the file
String filename = keyboard.next(); // the user response is stored
File inputFile = new File(filename+".txt"); // takes the filename and creates an object of the File class
Scanner fileIn = new Scanner(inputFile); // takes the object and converts the file to an obect of the Scanner class to allow it to be read
// creates an object of the ArrayList class
ArrayList<ACAdata> info = new ArrayList<>();
// variables declared for each column of data in the line
String state = " "; // State abbreviation
String org = " "; // Organizer of the ACA marketplace, either FFM for federally facilitated marketplace or SBM for state based marketplace.
double numEll = 0; // Number of citizens in the state eligible for ACA coverage
double numEn = 0; // Number of citizens who enrolled in an ACA plan
// while loop will evaluate as long as there are rows of data in the text file
while ( fileIn.hasNext() ) {
state = fileIn.next(); // individual state
org = fileIn.next(); // organization
numEll = fileIn.nextDouble(); // number of elligible citizens for that state for the Affordable Healthcare Act
numEn = fileIn.nextDouble(); // number of citizens enrolled in the Affordable Healthcare Act
double percentage = per( numEll, numEn ); // calls the per method to calculate a percentage for each state
// adds the 5 fields of data to a new ArrayList that holds the information for each state
info.add(new ACAdata( state, org, numEll, numEn, percentage));
}
// Prints out the information about the state
for ( int i = 0; i < info.size(); i++ ) {
System.out.println((info.get(i)).toString());
}
}
// method that finds the percentage of enrolled citizens that are elligible for the Affordable Care Act
public static double per( double Ell, double En ) {
double calculation = En / Ell * 100; // divides the Enrolled by the number of elligible citizens
return calculation; // returns the calculation
}
}
public class ACAdata {
// variables declared for each column of data in the line
String state = " "; // State abbreviation
String org = " "; // Organizer of the ACA marketplace, either FFM for federally facilitated marketplace or SBM for state based marketplace.
double numEll = 0; // Number of citizens in the state eligible for ACA coverage
double numEn = 0; // Number of citizens who enrolled in an ACA plan
double percentage = 0;
public ACAdata ( String state, String org, double numEll, double numEn, double percentage ) {
state = state;
org = org;
numEll = numEll;
numEn = numEn;
percentage = percentage;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public String getOrg() {
return this.org;
}
public void setOrg( String org ) {
this.org = org;
}
public double getNumEll() {
return this.numEll;
}
public void setNumEll( double numEll ) {
this.numEll = numEll;
}
public double getNumEn( double numEn ) {
return this.numEn;
}
public double getPercentage() {
return this.percentage;
}
public void setPercentage( double percentage ) {
this.percentage = percentage;
}
}
To make the ACAdata Object sortable.
If you have this Object you can sort it and then output it with.
ArrayList<ACAdata> list = new ArrayList<>();
Collections.sort(list);
for (Iterator<ACAdata> iterator = list.iterator(); iterator.hasNext();) {
ACAdata next = iterator.next();
System.out.println(next.toString());
}
public class ACAdata implements Comparable<ACAdata> {
// variables declared for each column of data in the line
String state = " "; // State abbreviation
String org = " "; // Organizer of the ACA marketplace, either FFM for federally facilitated marketplace or SBM for state based marketplace.
double numEll = 0; // Number of citizens in the state eligible for ACA coverage
double numEn = 0; // Number of citizens who enrolled in an ACA plan
double percentage = 0;
public ACAdata(String state, String org, double numEll, double numEn, double percentage) {
state = state;
org = org;
numEll = numEll;
numEn = numEn;
percentage = percentage;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public String getOrg() {
return this.org;
}
public void setOrg(String org) {
this.org = org;
}
public double getNumEll() {
return this.numEll;
}
public void setNumEll(double numEll) {
this.numEll = numEll;
}
public double getNumEn(double numEn) {
return this.numEn;
}
public double getPercentage() {
return this.percentage;
}
public void setPercentage(double percentage) {
this.percentage = percentage;
}
#Override
public int compareTo(ACAdata o) {
if (percentage > o.percentage) {
return -1;
}
if (percentage < o.percentage) {
return 1;
}
return 0;
}
#Override
public String toString() {
return "Put the info you want here!";
}
}
Looking at your code, the easiest solution (that I can think of) is to override toString in ACAdata with something like (add and format it how you want it)
#Override
public String toString() {
return String.format("%s %s %.2f %.2f", state, org, numEll, numEn);
}
And then you can just print the entire ArrayList, or individual ACAdata instances. You're already calling toString(), but you don't have to... Java will implicitly make a toString() call for you when you try and print an Object (the default implementation in Object just didn't do what you wanted).

Suggestions with GroceryList [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 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));
}

Can not get my subclass to send data back to main method for output

import java.text.DecimalFormat; // For proper currency
import java.util.Arrays;
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
Arrays.sort(aSoftware, new Comparator<Software>() {
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 year of copyright is "+ aSoftware[i].getYear());
System.out.println( "The restocking fee is "+ aSoftware[i].getRestockingFee());
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 main
public class Software
{
// Declare variables
String SoftwareTitle;
int SoftwareStock;
double SoftwarePrice;
int SoftwareNum;
double CalculateInventory;
double SoftwareValue;
double value;
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
//
public class Project3 extends Software
{
// Unique feature
private int year = 2012;
// Default Constructor
public Project3(String softtitle, int softstock, double softprice,int softitemnum, int year) {
super(softtitle, softstock, softprice, softitemnum);
this.year = year;
}
// Retuen Year
public int getYear()
{
return year;
}
// Set year
public void setYear(int year)
{
this.year = year;
}
// Calculate 5% restocking fee
public double getRestockingFee()
{
return getSoftwarePrice() * getSoftwareStock() * 0.05;
}
public double getCalculateInventory()
{
double value = 0;
for(int i = 0; i < 3; i++){
value = Softwarevalue();
}
return value;
}
}
My program runs fine except I can not get the my System out to pull over the getYear method and the getRestockingFee nethod from my Project 3 subclass. I could use a nudge in the right direction, I have to be missing something crazy.
The Java compiler, when given a Software object, has no way to know that it is really a Project3. In real life, if I put a Granny Smith apple in a box, and I tell you that there is an apple in the box, would you be able to tell me whether it boolean isGreen()? Java has the same problem!
There are possible 3 solutions:
When you construct the object, store it in a Project3 variable (and make sure the constructed type is a Project3!
Tell the JVM: "Hey this is really a Project3!" You can do this by casting the object to the correct time. Syntax ((Project3) mySoftware).getYear()
Define a meaning for the method getYear in the *super*class. This would be like telling you "hey, assume all Apples aren't green (isGreen() returns false)"... but if I know it's a Granny Smith subclass apple, isGreen returns true now!
Your choice of solution depends on what you want your system to do.

Categories

Resources