Advertisement
veronikaaa86

06. Students 2.0

Oct 27th, 2021
465
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.87 KB | None | 0 0
  1. package objectAndClasses;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.Scanner;
  6.  
  7. public class P06Students2 {
  8.  
  9. static class Student {
  10. String firstName;
  11. String lastName;
  12. String age;
  13. String town;
  14.  
  15. public Student(String firstName, String lastName, String age, String town) {
  16. this.firstName = firstName;
  17. this.lastName = lastName;
  18. this.age = age;
  19. this.town = town;
  20. }
  21.  
  22. public String getFirstName() {
  23. return firstName;
  24. }
  25.  
  26. public String getLastName() {
  27. return lastName;
  28. }
  29.  
  30. public String getAge() {
  31. return age;
  32. }
  33.  
  34. public String getTown() {
  35. return town;
  36. }
  37.  
  38. public void setAge(String age) {
  39. this.age = age;
  40. }
  41.  
  42. public void setTown(String town) {
  43. this.town = town;
  44. }
  45.  
  46. @Override
  47. public String toString() {
  48. return String.format("%s %s is %s years old%n",
  49. this.getFirstName(),
  50. this.getLastName(),
  51. this.getAge());
  52. }
  53. }
  54.  
  55. public static void main(String[] args) {
  56. Scanner scanner = new Scanner(System.in);
  57.  
  58. List<Student> studentsList = new ArrayList<>();
  59.  
  60. String input = scanner.nextLine();
  61. while (!input.equals("end")) {
  62. String[] inputLine = input.split(" ");
  63. String firstName = inputLine[0];
  64. String lastName = inputLine[1];
  65. String age = inputLine[2];
  66. String town = inputLine[3];
  67.  
  68. Student student = new Student(firstName, lastName, age, town);
  69.  
  70. int existingIndex = findStudentIndex(studentsList, student.getFirstName(), student.getLastName());
  71. if (existingIndex != - 1) {
  72. studentsList.get(existingIndex).setTown(student.town);
  73. studentsList.get(existingIndex).setAge(student.age);
  74. } else {
  75. studentsList.add(student);
  76. }
  77.  
  78. input = scanner.nextLine();
  79. }
  80.  
  81. String searchTownName = scanner.nextLine();
  82.  
  83. for (Student student : studentsList) {
  84. if (student.getTown().equals(searchTownName)) {
  85. System.out.print(student);
  86. }
  87. }
  88. }
  89.  
  90. static int findStudentIndex(List<Student> studentsList, String firstName, String lastName) {
  91. for (int i = 0; i < studentsList.size(); i++) {
  92. String firstNameList = studentsList.get(i).getFirstName();
  93. String lastNameList = studentsList.get(i).getLastName();
  94.  
  95. if (firstNameList.equals(firstName) && lastNameList.equals(lastName)) {
  96. return i;
  97. }
  98. }
  99.  
  100. return -1;
  101. }
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement