Advertisement
n_stefanov

Ex9_ListOfProducts

May 14th, 2014
412
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.59 KB | None | 0 0
  1. package javaLoopsMethodsClasses;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.io.BufferedReader;
  5. import java.io.BufferedWriter;
  6. import java.io.FileWriter;
  7. import java.io.FileReader;
  8. import java.io.Writer;
  9.  
  10. public class Ex9_ListOfProducts {
  11.  
  12.     public static void main(String[] args) {
  13.         ArrayList<Product> products = new ArrayList<Product>();
  14.         BufferedReader reader;
  15.         Writer writer = null;
  16.         try {
  17.             reader = new BufferedReader(new FileReader("Products.txt"));
  18.             String line = null;
  19.             while ((line = reader.readLine()) != null) {
  20.                String[] splittedLine = line.split(" ");
  21.                products.add(new Product(splittedLine[0], Double.parseDouble(splittedLine[1])));
  22.             }
  23.             Collections.sort(products);
  24.            
  25.             writer = new BufferedWriter(new FileWriter("Output.txt"));
  26.             for(Product product : products){
  27.                 writer.write(product.getPrice() + " " + product.getName() + "\r\n" );
  28.             }
  29.         }
  30.         catch (Exception e) {
  31.             System.out.println("Error");
  32.         }
  33.         finally {
  34.                try {writer.close();} catch (Exception ex) {}
  35.             }
  36.  
  37.     }
  38.  
  39. }
  40.  
  41.  
  42. class Product implements Comparable<Product>{
  43.     private String name;
  44.     private double price;
  45.    
  46.     public Product(String name, double price){
  47.         this.name = name;
  48.         this.price = price;
  49.     }
  50.    
  51.     public String getName(){
  52.         return name;
  53.     }
  54.    
  55.     public double getPrice(){
  56.         return price;
  57.     }
  58.    
  59.     public int compareTo(Product compareFruit) {
  60.          
  61.         double otherPrice = ((Product) compareFruit).getPrice();
  62.  
  63.         //ascending order
  64.         if(this.price>otherPrice) return 1;
  65.         else
  66.         if(this.price==otherPrice) return 0;
  67.         return -1;
  68.     }  
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement