I am coding with Java a function that checks if a date it's ok or not and want to jump up of the method if some condition is executed. I've read a similar question but hasn't the same trouble as it occurs in general and that's not what I want to ask.
public static void validar(String data) {
System.out.println (data);
if (data.indexOf(" ") == -1) {
System.out.println ("No hi ha separació entre data i temps");
System.out.println ("Data incorrecta" + "\n");
return;
}
else if (data.indexOf("-") == -1) {
System.out.println ("La data no conté un guions");
System.out.println ("Data incorrecta" + "\n");
return;
}
else if (data.indexOf(":") == -1) {
System.out.println ("El temps de la data no conté :'s");
System.out.println ("Data incorrecta" + "\n");
return;
}
...
It all works when done like this it:
2023-01-17 17:05:26
Data correcta
2023-01-1717:05:26
No hi ha separació entre data i temps
Data incorrecta
2023/01-17 17.05.26
El temps de la data no conté :'s
Data incorrecta
2023-01-17 17.05.26
El temps de la data no conté :'s
Data incorrecta
Have other conditions to check related to the date (if the date's length is 3 and the same for the time and much more) so I've created some array.
If I create them in the middle of the conditions like:
if (data.indexOf(" ") == -1) {
System.out.println ("No hi ha separació entre data i temps");
System.out.println ("Data incorrecta" + "\n");
return;
}
else if (data.indexOf("-") == -1) {
System.out.println ("La data no conté un guions");
System.out.println ("Data incorrecta" + "\n");
return;
}
else if (data.indexOf(":") == -1) {
System.out.println ("El temps de la data no conté :'s");
System.out.println ("Data incorrecta" + "\n");
return;
}
String[] arrDiaHora = data.split(" ");
String diamesany = arrDiaHora[0];
String horaminutsegon = arrDiaHora[1];
String[] arrDiaMesAny = diamesany.split("-");
String strany = arrDiaMesAny[0];
String strmes = arrDiaMesAny[1];
String strdia = arrDiaMesAny[2];
String[] arrHoraMinutSegon = horaminutsegon.split(":");
String strhora = arrHoraMinutSegon[0];
String strminut = arrHoraMinutSegon[1];
String strsegon = arrHoraMinutSegon[2];
if (arrDiaHora.length != 2) {
System.out.println ("No hi ha dos blocs formats per data i temps");
System.out.println ("Data incorrecta" + "\n");
return;
}
...
Return values after the arrays don't work and get 'return' is unnecessary as the last statement in a 'void' method.
If I create the arrays before checking the conditions, I got an ArrayIndexOutOfBoundsException
Any help ?
Thanks in advance !!