Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.List;
- import java.util.NoSuchElementException;
- import java.util.Scanner;
- public class Application {
- public static void main(String[] args) {
- try (
- BufferedReader reader = new BufferedReader ( new FileReader("people.txt")))
- {
- String line = reader.readLine();
- Scanner scan = null;
- String surname = null;
- String firstName = null;
- double salary = 0.0;
- List<Person> list = new ArrayList<>();
- while(line != null)
- {
- scan = new Scanner(line);
- surname = scan.next();
- firstName = scan.next();
- salary = scan.nextDouble();
- list.add(new Person(surname, firstName,salary));
- line = reader.readLine();
- }
- System.out.println("Original persons list:");
- System.out.println("Surname \tFirstName\tSalary");
- for(int i = 0; i< list.size();i++)
- {
- System.out.print(list.get(i).getSurname() + " " + "\t" + list.get(i).getFirstName() + "\t\t" + list.get(i).getSalary() + "\n");
- }
- System.out.println("\n"+"Enter whether you would like the list sorted by 'Name' or 'Salary'");
- Scanner scan1 = new Scanner(System.in);
- String option = scan1.next().toLowerCase();
- if(option.equals("name"))
- {
- Collections.sort(list); //sorts by name
- System.out.println("\n" + "Sorted by surname then by first name:");
- }
- else if(option.equals("salary"))
- {
- Collections.sort(list, new PersonComparator()); //sorts by salary
- System.out.println("\n" + "Sorted by salary:");
- }
- else
- {
- System.out.println("Invalid option");
- System.exit(0);
- }
- System.out.println("Surname \tFirstName\tSalary");
- for(int i = 0; i< list.size();i++)
- {
- System.out.print(list.get(i).getSurname() + " " + "\t" + list.get(i).getFirstName() + "\t\t" + list.get(i).getSalary());
- System.out.println();
- }
- scan1.close();
- }
- catch(FileNotFoundException e)
- {
- System.out.println(e);
- }
- catch(IOException e)
- {
- System.out.println(e);
- }
- catch(NoSuchElementException e)
- {
- System.out.println("One of the lines in the text file doesn't have all the required fields");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement