Hello, I go to Run -> Edit configurations -> I add the program arguments -c Washington m "04 15 1990".
This, normally should create a new person and add it to the list, no? At least this is what I understand from the switch case "-c".
Then, I go back to Run -> Edit configurations -> I add the program arguments -i 2 .
This, normally then should print the information of the 3 elements of the arraylist.
In main, I print args[2]; however I get the ArrayIndexOutOfBounds error which means the arguments from the beginning were not added to the array list.
What is happening?
public class Solution {
public static List<Person> allPeople = new ArrayList<>();
static {
allPeople.add(Person.createMale("Donald Chump", new Date())); // id=0
allPeople.add(Person.createMale("Larry Gates", new Date())); // id=1
}
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM dd yyyy", Locale.ENGLISH);
private static SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("MMM dd yyyy", Locale.ENGLISH);
public static void main(String[] args) throws Exception {
//for (int i = 0; i < args.length; i++){
System.out.println(args[0]);
//}
if (args == null || args.length < 1)
throw new RuntimeException();
Date birthdayDate;
Person person;
switch (args[0]) {
case "-c":
birthdayDate = simpleDateFormat.parse(args[3]);
if (args[2].equals("m"))
person = Person.createMale(args[1], birthdayDate);
else
person = Person.createFemale(args[1], birthdayDate);
allPeople.add(person);
System.out.println(allPeople.size() - 1);
break;
case "-u":
birthdayDate = simpleDateFormat.parse(args[4]);
int id = Integer.parseInt(args[1]);
person = allPeople.get(id);
if (person == null)
throw new IllegalArgumentException();
person.setSex(getSex(args[3]));
person.setBirthDate(birthdayDate);
person.setName(args[2]);
allPeople.set(id, person);
break;
case "-d":
Person currentPerson = allPeople.get(Integer.valueOf(args[1]));
currentPerson.setName(null);
currentPerson.setSex(null);
currentPerson.setBirthDate(null);
break;
case "-i":
person = allPeople.get(Integer.parseInt(args[1]));
if (person != null)
System.out.println(person.getName() + " " + (person.getSex() == Sex.MALE ? "m" : "f") + " " + simpleDateFormat2.format(person.getBirthDate()));
break;
}
}
private static Sex getSex(String sexParam) {
return sexParam.equals("m") ? Sex.MALE : Sex.FEMALE;
}
}