Advertisement
desislava_topuzakova

06. Order by Age

Oct 29th, 2022
315
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. package orderByAge;
  2.  
  3. public class Person {
  4. //полета -> характеристики -> име, ID, възраст
  5. private String name;
  6. private String id;
  7. private int age;
  8.  
  9. //конструктор -> създавам обекти от класа
  10. public Person(String name, String id, int age) {
  11. //нов празен обект (name = null, id = null, age = 0)
  12. this.name = name;
  13. this.id = id;
  14. this.age = age;
  15. }
  16.  
  17. public int getAge() {
  18. return this.age;
  19. }
  20.  
  21. @Override
  22. public String toString() {
  23. //"{name} with ID: {id} is {age} years old."
  24. return String.format("%s with ID: %s is %d years old.", this.name, this.id, this.age);
  25. }
  26. }
  27.  
  28. package orderByAge;
  29.  
  30. import java.util.ArrayList;
  31. import java.util.Comparator;
  32. import java.util.List;
  33. import java.util.Scanner;
  34.  
  35. public class Main {
  36. public static void main(String[] args) {
  37. Scanner scanner = new Scanner(System.in);
  38. List<Person> personList = new ArrayList<>();
  39. String input = scanner.nextLine();
  40.  
  41. while (!input.equals("End")) {
  42. //input -> данни за даден човек
  43. //input = "Desislava 1234 24".split(" ") -> ["Desislava", "1234", "24"]
  44. String name = input.split(" ")[0];
  45. String id = input.split(" ")[1];
  46. int age = Integer.parseInt(input.split(" ")[2]);
  47.  
  48. Person person = new Person(name, id, age);
  49. personList.add(person);
  50.  
  51. input = scanner.nextLine();
  52. }
  53.  
  54. //списък с хора
  55. //1. сортираме по възраст (в нарастващ ред -> ascending order)
  56. personList.sort(Comparator.comparing(Person::getAge));
  57. //2. принтираме всеки човек
  58. for (Person person : personList) {
  59. //"{name} with ID: {id} is {age} years old."
  60. System.out.println(person);
  61. }
  62. }
  63. }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement