Advertisement
dimipan80

List of Products (using User Defined Class Product)

Aug 20th, 2014
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.89 KB | None | 0 0
  1. /* Read from a text file named "Input.txt" a list of products.
  2.  * Each product will be in format name + space + price.
  3.  * You should hold the products in objects of class Product.
  4.  * Sort the products by price and write them in format price + space + name
  5.  * in a file named "Output.txt". Ensure you close correctly all used resources. */
  6.  
  7. import java.io.File;
  8. import java.io.FileNotFoundException;
  9. import java.io.IOException;
  10. import java.io.PrintStream;
  11. import java.util.ArrayList;
  12. import java.util.Collections;
  13. import java.util.Locale;
  14. import java.util.Scanner;
  15.  
  16. public class _09_ListOfProducts {
  17.  
  18.     public static void main(String[] args) {
  19.         // TODO Auto-generated method stub
  20.         Locale.setDefault(Locale.ROOT);
  21.         ArrayList<Product> productList = readInputTextFileAndCreateListOfProducts();
  22.         Collections.sort(productList);
  23.         printTheSortedListInOutputTextFile(productList);
  24.     }
  25.  
  26.     private static ArrayList<Product> readInputTextFileAndCreateListOfProducts() {
  27.         ArrayList<Product> products = new ArrayList<Product>();
  28.         File file = new File("Input.txt");
  29.         try (Scanner scan = new Scanner(file);) {
  30.             while (scan.hasNextLine()) {
  31.                 String inputLine = scan.nextLine();
  32.                 String[] inputs = inputLine.split("[ ]+");
  33.                 Product nextProduct = new Product(inputs[0], inputs[1]);
  34.                 products.add(nextProduct);
  35.             }
  36.         } catch (FileNotFoundException e) {
  37.             System.out.println("Error! - The Input text File is Not Found!!!");
  38.             e.printStackTrace();
  39.         }
  40.  
  41.         return products;
  42.     }
  43.  
  44.     private static void printTheSortedListInOutputTextFile(
  45.             ArrayList<Product> products) {
  46.         File file = new File("Output.txt");
  47.         try (PrintStream writer = new PrintStream(file);) {
  48.             for (Product product : products) {
  49.                 writer.println(product.toString());
  50.             }
  51.         } catch (IOException e) {
  52.             System.out.println("Error! - Has a Problem with Output text File!!!");
  53.             e.printStackTrace();
  54.         }
  55.     }
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement