Валидатор пишет:
"Каждый case оператора switch должен иметь блок синхронизации по allPeople. Убедись, что метод main содержит оператор switch по значению args[0]."
Не пойму, что он хочет. По идее, надо блок синхронизации в каждый метод ставить, а не в switch, но так записано в задании.
package com.javarush.task.task17.task1711;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/*
CRUD 2
*/
public class Solution {
public static volatile List<Person> allPeople = new ArrayList<Person>();
static {
allPeople.add(Person.createMale("Иванов Иван", new Date())); //сегодня родился id=0
allPeople.add(Person.createMale("Петров Петр", new Date())); //сегодня родился id=1
}
public static void main(String[] args) {
if(args.length==0)
return;
try {
switch (args[0]) {
case "-c":
synchronized (allPeople) {
addPerson(args);
}
break;
case "-u":
synchronized (allPeople){
updatePerson(args);
}
break;
case "-d":
synchronized (allPeople){
deletePerson(args);
}
break;
case "-i":
synchronized (allPeople){
printAllPersonsForBirthdate(args);
}
break;
default:
System.out.println("Неверный аргумент!");
}
//System.out.println(allPeople);
}catch (ParseException e){
e.printStackTrace();
}
}
private static void addPerson(String[] args) throws ParseException {
Date birthDate;
Person person = null;
//int numberOfPerson = (args.length-1)/3;
for (int i = 1; i < args.length; i+=3) {
birthDate = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH).parse(args[i+2]);
if(args[i+1].equals("м") ) {
person = Person.createMale(args[i], birthDate);
}else if(args[i+1].equals("ж")) {
person = Person.createFemale(args[i], birthDate);
}
allPeople.add(person);
System.out.println(allPeople.size()-1);
}
}
private static void updatePerson(String[] args) throws ParseException{
Date birthDate;
try {
for (int i = 1; i < args.length; i+=4) {
Person person = allPeople.get(Integer.parseInt(args[i]));
person.setName(args[i+1]);
if (args[i+2].equals("м"))
person.setSex(Sex.MALE);
else if (args[i+2].equals("ж"))
person.setSex(Sex.FEMALE);
birthDate = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH).parse(args[i+3]);
person.setBirthDate(birthDate);
}
}catch (IndexOutOfBoundsException e){
System.out.println("Нет такого человека!");
}
}
private static void deletePerson(String[] args){
Person person;
for (int i = 1; i < args.length; i++) {
person = allPeople.get(Integer.parseInt(args[i]));
if(person != null){
person.setName(null);
person.setSex(null);
person.setBirthDate(null);
}
}
}
private static void printAllPersonsForBirthdate(String[] args){
for (int i = 1; i < args.length; i++) {
System.out.println(allPeople.get(Integer.parseInt(args[i])));
}
}
}