Advertisement
Guest User

Untitled

a guest
Nov 14th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.FileNotFoundException;
  3. import java.io.FileReader;
  4. import java.io.IOException;
  5. import java.util.ArrayList;
  6. import java.util.Collections;
  7. import java.util.List;
  8. import java.util.NoSuchElementException;
  9. import java.util.Scanner;
  10.  
  11.  
  12. public class Application {
  13.  
  14. public static void main(String[] args) {
  15. try (
  16. BufferedReader reader = new BufferedReader ( new FileReader("people.txt")))
  17. {
  18. String line = reader.readLine();
  19. Scanner scan = null;
  20. String surname = null;
  21. String firstName = null;
  22. double salary = 0.0;
  23. List<Person> list = new ArrayList<>();
  24.  
  25. while(line != null)
  26. {
  27. scan = new Scanner(line);
  28. surname = scan.next();
  29. firstName = scan.next();
  30. salary = scan.nextDouble();
  31. list.add(new Person(surname, firstName,salary));
  32. line = reader.readLine();
  33. }
  34.  
  35. System.out.println("Original persons list:");
  36. System.out.println("Surname \tFirstName\tSalary");
  37. for(int i = 0; i< list.size();i++)
  38. {
  39. System.out.print(list.get(i).getSurname() + " " + "\t" + list.get(i).getFirstName() + "\t\t" + list.get(i).getSalary() + "\n");
  40. }
  41.  
  42. System.out.println("\n"+"Enter whether you would like the list sorted by 'Name' or 'Salary'");
  43. Scanner scan1 = new Scanner(System.in);
  44. String option = scan1.next().toLowerCase();
  45.  
  46. if(option.equals("name"))
  47. {
  48. Collections.sort(list); //sorts by name
  49. System.out.println("\n" + "Sorted by surname then by first name:");
  50. }
  51.  
  52. else if(option.equals("salary"))
  53. {
  54. Collections.sort(list, new PersonComparator()); //sorts by salary
  55. System.out.println("\n" + "Sorted by salary:");
  56. }
  57.  
  58. else
  59. {
  60. System.out.println("Invalid option");
  61. System.exit(0);
  62. }
  63.  
  64. System.out.println("Surname \tFirstName\tSalary");
  65. for(int i = 0; i< list.size();i++)
  66. {
  67. System.out.print(list.get(i).getSurname() + " " + "\t" + list.get(i).getFirstName() + "\t\t" + list.get(i).getSalary());
  68. System.out.println();
  69. }
  70. scan1.close();
  71. }
  72.  
  73. catch(FileNotFoundException e)
  74. {
  75. System.out.println(e);
  76. }
  77. catch(IOException e)
  78. {
  79. System.out.println(e);
  80. }
  81. catch(NoSuchElementException e)
  82. {
  83. System.out.println("One of the lines in the text file doesn't have all the required fields");
  84. }
  85. }
  86.  
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement