tockata

Problem 9. ListOfProducts - Java Loops, Method, Classes.

May 21st, 2014
378
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.94 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.BufferedWriter;
  3. import java.io.File;
  4. import java.io.FileReader;
  5. import java.io.FileWriter;
  6. import java.io.IOException;
  7. import java.math.BigDecimal;
  8. import java.util.ArrayList;
  9. import java.util.Collections;
  10.  
  11.  
  12. public class _09_ListOfProducts {
  13.     public static void main(String[] args) {
  14.         ArrayList<Product> products = new ArrayList<>();
  15.        
  16.         try {
  17.             BufferedReader fileReader = new BufferedReader(new FileReader("src/input1.txt"));
  18.             File fileProducts = new File("src/products.txt");
  19.             fileProducts.createNewFile();
  20.             BufferedWriter fileWriter = new BufferedWriter(new FileWriter("src/products.txt"));
  21.             while (true) {
  22.                 String line = fileReader.readLine();
  23.                 if (line == null) {
  24.                     fileReader.close();
  25.                     break;
  26.                 }
  27.                 String[] input = line.split(" ");
  28.                 products.add(new Product(input[0], new BigDecimal(input[1])));
  29.             }
  30.             Collections.sort(products);
  31.             for (Product product : products) {
  32.                 System.out.println(product.getName() + " " + product.getPrice());
  33.                 fileWriter.write(product.getName() + " " + product.getPrice());
  34.                 fileWriter.newLine();
  35.             }
  36.             fileWriter.close();
  37.         }catch (IOException e) {
  38.             System.out.println("Error!");
  39.         }
  40.     }
  41.    
  42. }
  43.  
  44. class Product implements Comparable<Product> {
  45.     private String name;
  46.     private BigDecimal price;
  47.    
  48.     public Product(String name, BigDecimal price) {
  49.         super();
  50.         this.name = name;
  51.         this.price = price;
  52.     }
  53.  
  54.     public String getName() {
  55.         return name;
  56.     }
  57.     public void setName(String name) {
  58.         this.name = name;
  59.     }
  60.     public BigDecimal getPrice() {
  61.         return price;
  62.     }
  63.     public void setPrice(BigDecimal price) {
  64.         this.price = price;
  65.     }
  66.     public int compareTo(Product compareProduct) {
  67.          
  68.         BigDecimal comparePrice = ((Product)compareProduct).getPrice();
  69.  
  70.         //ascending order
  71.         return this.price.compareTo(comparePrice);
  72.  
  73.         //descending order
  74.         //return comparePrice.compareTo(this.price);
  75.  
  76.     }  
  77. }
Advertisement
Add Comment
Please, Sign In to add comment