Probably really simple solution!
Hey guys, basically i have been asked to create a program that helps a shop manage its art gallery. i am stuck on the method that allows me to print my ArrayList<Art> collection; in order of value. i can print out all elements of collection no problem but i cannot sort for some reason.
i have tried using implements Comparable<collection> but i get the error cannot find class, and saying it is not an abstract class so it cannot overide compareTo method. but i dont have a compare to method :)
Code:
import java.util.*;
import java.io.*;
public class Inventory
{
private Art a; //holds the Art class and allows piece collection
private String name;
private Scanner scan; //allows user input
private int total; //total value of the collection
private List<Art> collection;
private int nextFreeLocation; //used to determine size
private int capacity;
private double sessionTotal; //allows me to keep a running total for session
public double VAT=0.2; //public variable for VAT
public Inventory(int maxCollectionSize)
{
nextFreeLocation=0; //empty array so next free location is 0
capacity=maxCollectionSize;
scan=new Scanner(System.in);
collection=new ArrayList<Art>(capacity);
}
/**
* This method sets the name attribute
* this method allows us to name the inventory
* example "ChrisShop"
*
* @param inventoryName
*/
public void setName(String inventoryName)
{
inventoryName=name;
}
/**
* This method allows us to return the name of the inventory
*
* example return "ChrisShop"
*
* @return String
*/
public String getName()
{
return name;
}
/**
* This methods allows us to "count" the elements in the inventory
* it does this by returning the next free 'space'
*
* @return int
*/
public int getNumOfPieces()
{
return nextFreeLocation;
}
/**
* This method allows the user to create a piece to add to inventory
* this is ran externally through the Menu class
* it is called when the user inputs the correct input:
* this case being '1'
* @param Art a
*
*/
public void addArt(Art a)
{
a=new Art();
System.out.println("enter name of artist \n");
String artist=scan.nextLine();
System.out.print("enter name of art piece \n");
String name=scan.nextLine();
System.out.print("Enter value of art piece \n");
int value=scan.nextInt();
System.out.print("Enter file name of art piece \n");
String image=scan.nextLine();
//finished constructing dog(x, x, x);
a=new Art(artist, name, value, image);
collection.add(a);
}
/**
* prints information about the pieces in Inventory
*
* @return String
*/
public String toString() {
/*code adapted from worksheet 5-daphne, by Lynda
* added my own class names and toString
*/
String results = "Pieces in Shops Invetory are:";
for (Art a:collection)
{
results = results + a.toString() + "\n";
}
return results;
}
/**
* save() method writes data back to file
* this will write all the to strings for each piece in collection
* to the specified text file called from UserMenu in Menu class
* try catch block prevents bombing, as expecption is caught and handled
* @param fileName file to write to called in UserMenu
*/
public void save(String fileName)
{
/*
* adapted from Lynda's Contact code, made it handle my arrays
* and my art toString
*/
System.out.println("**method save writes data back to a file "+fileName);
try {
PrintWriter outfile = new PrintWriter(new OutputStreamWriter
(new FileOutputStream(fileName)));
outfile.println(collection.size());
for (Art a:collection) {
/*
* reason i have adapted this code as follows:
* if i chose to to a.tostring it would cause my load method to bomb
* This way saving each variable to a new line allows
* my load method to read the same file allowing me to save/load
* *
*/
outfile.println(a.getArtist()); //stores only this variable
outfile.println(a.getTitle());
outfile.println(a.getValue());
outfile.println(a.getFileName());
//can also use any other art method such as getValue
}
outfile.close();
}
catch (IOException e) {
System.out.println("file not found try again");
//trycatch prevents bombing
}
}
/**
* load() method reads from a file
* @param fileName file to read from
* the file must be of the form
* hense why save method prints variables instead of a.toString
* 5(X) (num) must match the amount of art pieces in the file
*artist
*title
*value
*filename - must include file extension e.g xxx.jpeg
*called from UserMenu in Menu class
* try catch block prevents bombing, as expecption is caught and handled
*/
public void load(String fileName){
/*
* Code adapted from Lynda's worksheet 5 - Daphne
* adapted to understand my code and arrays
*/
try // prevents crashing if no exsistent file is inputted
{
{
System.out.println("reads using file "+fileName);
Scanner infile =new Scanner(new InputStreamReader
(new FileInputStream(fileName)));
int num=infile.nextInt(); // counts lines in file ready for loop:
for (int i=0;i<num;i++) { //loops through everyline in the file
String artist=infile.next(); //check for next string in the file and it becomes name
String name=infile.next(); //check for next string in file it becomes owner
int value=infile.nextInt();//checks for next int it becomes value
String image=infile.next();
Art a=new Art(artist, name, value, image); //created new art piece using these variables from file
collection.add(a); //adds the new piece(a) based off file read and loaded
}
infile.close();
}
}
catch (IOException e)
{
System.out.println("File not found - please try again");
}
}
public void print() {
System.out.println("The pieces in the Inventory are: \n");
for(Art a: collection){
System.out.println(a.toString()); //executes Art toString
Collection.sort(collection);
}
}
public void totalValue()
{
/*
*Below method taken from useful collections worksheet
*i have ammended the code to allow for use within my project
* added total as my own variable
* allowed it to serach my collections list
*
*/
Scanner avg=new Scanner(System.in);//for use in calling avg method
String q;//for use in calling avg method
int subTotal=0;
for(Art a:collection){
subTotal += a.getValue();
}
total=subTotal; //gives total a value for sue with other methods
System.out.println("Total value of collection is: £"+total);
System.out.println("Would like to find the average value of collection? (yes or no)");;
q=scan.nextLine();
if(q.equals("yes")){
averageValue();
}else {
return; //jumps out of method
}
}
private void averageValue()
{
/*
* set method to private so it cant be called before total value is calculated
* will be called after totalValue has been called so it has data to
* calculate and prevent errors.
*/
double averageValue=total/collection.size();
System.out.println("The average Value of the collection is £"+averageValue);
return;
}
/**
* Enables a user to delete Search the collection for an Ar piece.
* Searches the ArrayList<Art> collection: for "title"
* if it find this it will display the toString(a),
* return jumps it out the method so after it finds the piece so method is stopped
* @param title
*/
public void searchForPiece(String title) {
/*
* The below code has been adapted from my own worksheet 5/6 in CS122.
* the way in which i created this method was to use information provided by Lynda on searching arrays
* then created an equals and something to return accordingly
* *
*search for Art and print toString
*/
for (Art a:collection) {
if (title.equals(a.getTitle())) {
System.out.println(a.toString());
return; //jump out of method
}
}
System.out.println("Piece not in collection, please try again");
}
/**
* Enables a user to delete Search the collection for an Art
* piece also prints recipt and removes piece if sold
* Searches the ArrayList<Art> collection: for "title"
* if it find this it will display the toString(a),
* return jumps it out the method so after it finds the piece so method is stopped
* @param title
*/
public void SellPieceAndRecipt(String title) {
/*
* The below code has been adapted from my own worksheet 5/6 in CS122.
* the way in which i created this method was to use information provided by Lynda on searching arrays
* then created an equals and something to return accordingly
* *
*search for Art and remove from array list whilst printing a "recipt"
*/
for (Art a:collection) {
if (title.equals(a.getTitle())) { //title = search param "String title"
/*
* creating the recipt, adding variables as needed some methods acces each other
* also since selling an Art piece removes it from array i used a scanner
* to confirm sale (removal) to avoid accidental deleted
* recipt will be printed before this is asked
* recipt all created by me using standard println and
* creating suitable variables and simple math for calcs.
* also if the piece is sold it will display a running total for this 'session'
*
*/
//start of recipt and variables
double c; //for use with payment
System.out.println("********** TRANSACTION RECIPT *******");
System.out.println(" The transaction is as follows ");
System.out.println(" Piece name " +title);
int price=a.getValue();
System.out.println(" Price £" +price);
double vatTotal=price*VAT;
System.out.println(" VAT @ 20% £"+vatTotal);
double rest=price-vatTotal; //calculating price after vat been deducted
System.out.println(" Sale price -VAT £"+rest);
double artistOwed=rest*0.75; //creating artist owed variable 75%
System.out.println(" Artist owed (75% of fee) £"+artistOwed);
double gallery=rest*0.25; //25% percentage calc
System.out.println(" Gallery recieves £" +gallery);
System.out.println(" Total for sale £"+price);
//end of recipt print
//confirm sale using scanner, thus removing piece
String q;//input variable for scanner
System.out.println("Would to complete sale? (yes or no)");
q=scan.nextLine(); //user responce
if(q.equals("yes")){
sessionTotal += price; // keeps a running total of the sales
collection.remove(a);
System.out.println("Item sold, thank you for your custom!" );
System.out.println("Total for this session £"+sessionTotal); //displays total for this session based on sales
return; //jumps out of method
}else {
System.out.println(" Transaction incomplete, item not removed");
System.out.println(" ******** END ******");
return; //jumps out of method
}
}
}
System.out.println("Piece not in collection, please try again");
}
}
That class has the array list i need to sort in
This class (Art) are the elements of the array list
Code:
public class Art
{
private String artist;
private String title;
private int value;
private String filename;
public Art()
{
artist="unknown";
title="unknown";
value=0;
}
public Art(String artistName, String pieceTitle, int worth, String image)
{
artist=artistName;
title=pieceTitle;
value=worth;
filename=image;
}
public void setArtist(String artistName)
{
artistName=artist;
}
public String getArtist()
{
return artist;
}
public void setTitle (String pieceName)
{
pieceName=title;
}
public String getTitle()
{
return title;
}
public void setValue(int worth)
{
worth=value;
}
public int getValue()
{
return value;
}
public void setFileName(String image)
{
image=filename;
}
public String getFileName()
{
return filename;
}
public String toString(){
if (value==0) {
return " This piece is by " +artist+ " and is called " +title+ " and has no value" ;
}
else {
return " This piece is by " +artist+ " and is called " +title+ " and is worth £"+value;
}
}
}
any ideas?
Thanks.
Re: Probably really simple solution!
Perhaps this would be useful to you?
How to sort an ArrayList in java
Re: Probably really simple solution!
i tried many websites like that, but the point im trying to make is i cant use Collection.sort(collection);
i get the error message:
no suitable method found for sort(java,util.List<Art>
method java.util.Collections<T>sort(java.util.List<T>,jav a.util.Comparator<? super T> is not applicable;
(cannot instantiate from arguments because actual and formal arguments differ in length);
Re: Probably really simple solution!
Quote:
Originally Posted by
monkeyjr97
i tried many websites like that, but the point im trying to make is i cant use Collection.sort(collection);
i get the error message:
no suitable method found for sort(java,util.List<Art>
method java.util.Collections<T>sort(java.util.List<T>,jav a.util.Comparator<? super T> is not applicable;
(cannot instantiate from arguments because actual and formal arguments differ in length);
Make your Art class implement the Comparable<Art> interface; you must implement one single method in that class: public int compareTo(Art a) { ... } Read the API documentation for the Comparable<T> interface for details.
kind regards,
Jos
Re: Probably really simple solution!
monkeyjr97, please go through the Forum Rules -- particularly the third paragraph.
db
Re: Probably really simple solution!
sorry DarrylBurke!
got it all working now cheers guys!