Advertisement
desislava_topuzakova

07. Order by Age

Jul 3rd, 2022
1,539
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.94 KB | None | 0 0
  1. клас Person:
  2. package orderByAge;
  3.  
  4. public class Person {
  5.     //полета -> характеристики
  6.     private String name;
  7.     private String id;
  8.     private int age;
  9.  
  10.     //конструктор
  11.     public Person(String name, String id, int age) {
  12.         this.name = name;
  13.         this.id = id;
  14.         this.age = age;
  15.     }
  16.  
  17.     //GETTERS AND SETTERS
  18.     public String getName() {
  19.         return name;
  20.     }
  21.  
  22.     public void setName(String name) {
  23.         this.name = name;
  24.     }
  25.  
  26.     public String getId() {
  27.         return id;
  28.     }
  29.  
  30.     public void setId(String id) {
  31.         this.id = id;
  32.     }
  33.  
  34.     public int getAge() {
  35.         return age;
  36.     }
  37.  
  38.     public void setAge(int age) {
  39.         this.age = age;
  40.     }
  41. }
  42.  
  43.  
  44. клас Main:
  45.  
  46. package orderByAge;
  47.  
  48. import java.util.ArrayList;
  49. import java.util.Comparator;
  50. import java.util.List;
  51. import java.util.Scanner;
  52.  
  53. public class Main {
  54.     public static void main(String[] args) {
  55.         Scanner scanner = new Scanner(System.in);
  56.         List<Person> personList = new ArrayList<>();
  57.         String personalData = scanner.nextLine();
  58.  
  59.         while (!personalData.equals("End")) {
  60.             //"George 123456 20".split(" ") -> ["George", "123456", "20"]
  61.             String name = personalData.split(" ")[0];
  62.             String id = personalData.split(" ")[1];
  63.             int age = Integer.parseInt(personalData.split(" ")[2]);
  64.  
  65.             Person person = new Person(name, id, age);
  66.             personList.add(person);
  67.  
  68.             personalData = scanner.nextLine();
  69.         }
  70.  
  71.         //списък с обекти от клас Person
  72.         personList.sort(Comparator.comparing(Person :: getAge));
  73.  
  74.         for (Person person : personList) {
  75.             //"Stephan with ID: 524244 is 10 years old."
  76.             System.out.printf("%s with ID: %s is %d years old.%n", person.getName(), person.getId(), person.getAge());
  77.         }
  78.     }
  79. }
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement