Advertisement
Guest User

9. List of Products

a guest
May 21st, 2014
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.46 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.io.PrintWriter;
  4. import java.text.DecimalFormat;
  5. import java.util.ArrayList;
  6. import java.util.Collections;
  7. import java.util.Locale;
  8. import java.util.Scanner;
  9.  
  10.  
  11. public class _09_ListOfProducts {
  12.     public static void main(String args[]) {
  13.  
  14.         Locale.setDefault(Locale.ROOT);
  15.         File file = new File("ListOfProducts/input.txt");
  16.         ArrayList<Product> products = new ArrayList<Product>();
  17.         try {
  18.             Scanner sc = new Scanner(file);
  19.             while (sc.hasNext()) {
  20.                 products.add(new Product(sc.next(), sc.nextDouble()));
  21.             }
  22.         } catch (FileNotFoundException e) {
  23.             System.out.println("Error");
  24.         }
  25.        
  26.         Collections.sort(products);
  27.         try {
  28.             PrintWriter pw = new PrintWriter (new File("ListOfProducts/output.txt"));
  29.             for (Product product : products) {
  30.                 pw.println(product.toString());
  31.             }
  32.             pw.close();
  33.         } catch (FileNotFoundException e) {
  34.             e.printStackTrace();
  35.         }
  36.        
  37.     }
  38.  
  39.    
  40.    
  41. }
  42. class Product implements Comparable <Product>{
  43.     private String name;
  44.     private double price;
  45.     Product (String name, double price) {
  46.         this.name = name;
  47.         this.price = price;
  48.     }
  49.     @Override
  50.     public String toString() {
  51.         DecimalFormat formatter = new DecimalFormat("#0.00");
  52.         return formatter.format(this.price) + " " + this.name;
  53.     }
  54.     @Override
  55.     public int compareTo(Product arg) {
  56.         if(this.price < arg.price)
  57.             return -1;
  58.         else if (this.price > arg.price)
  59.             return 1;
  60.         return 0;
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement