Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.math.BigDecimal;
- import java.util.ArrayList;
- import java.util.Collections;
- public class _09_ListOfProducts {
- public static void main(String[] args) {
- ArrayList<Product> products = new ArrayList<>();
- try {
- BufferedReader fileReader = new BufferedReader(new FileReader("src/input1.txt"));
- File fileProducts = new File("src/products.txt");
- fileProducts.createNewFile();
- BufferedWriter fileWriter = new BufferedWriter(new FileWriter("src/products.txt"));
- while (true) {
- String line = fileReader.readLine();
- if (line == null) {
- fileReader.close();
- break;
- }
- String[] input = line.split(" ");
- products.add(new Product(input[0], new BigDecimal(input[1])));
- }
- Collections.sort(products);
- for (Product product : products) {
- System.out.println(product.getName() + " " + product.getPrice());
- fileWriter.write(product.getName() + " " + product.getPrice());
- fileWriter.newLine();
- }
- fileWriter.close();
- }catch (IOException e) {
- System.out.println("Error!");
- }
- }
- }
- class Product implements Comparable<Product> {
- private String name;
- private BigDecimal price;
- public Product(String name, BigDecimal price) {
- super();
- this.name = name;
- this.price = price;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public BigDecimal getPrice() {
- return price;
- }
- public void setPrice(BigDecimal price) {
- this.price = price;
- }
- public int compareTo(Product compareProduct) {
- BigDecimal comparePrice = ((Product)compareProduct).getPrice();
- //ascending order
- return this.price.compareTo(comparePrice);
- //descending order
- //return comparePrice.compareTo(this.price);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment