英文:
Return keyword in void method not always working JAVA
问题
I understand your code and the issue you're facing. It seems you want to validate a date and time string in Java. Here's the translated code with comments on where the issue might occur:
public static void validate(String data) {
System.out.println(data);
// Check for spaces in the input
if (data.indexOf(" ") == -1) {
System.out.println("No space between date and time");
System.out.println("Incorrect data" + "\n");
return;
}
// Check for hyphens in the date part
else if (data.indexOf("-") == -1) {
System.out.println("Date does not contain hyphens");
System.out.println("Incorrect data" + "\n");
return;
}
// Check for colons in the time part
else if (data.indexOf(":") == -1) {
System.out.println("Time in date does not contain colons");
System.out.println("Incorrect data" + "\n");
return;
}
// Split the input into date and time
String[] arrDiaHora = data.split(" ");
String diamesany = arrDiaHora[0];
String horaminutsegon = arrDiaHora[1];
// Split the date into year, month, and day
String[] arrDiaMesAny = diamesany.split("-");
String strany = arrDiaMesAny[0];
String strmes = arrDiaMesAny[1];
String strdia = arrDiaMesAny[2];
// Split the time into hour, minute, and second
String[] arrHoraMinutSegon = horaminutsegon.split(":");
String strhora = arrHoraMinutSegon[0];
String strminut = arrHoraMinutSegon[1];
String strsegon = arrHoraMinutSegon[2];
// Check if there are two parts (date and time)
if (arrDiaHora.length != 2) {
System.out.println("No two blocks for date and time");
System.out.println("Incorrect data" + "\n");
return;
}
// Additional date and time validation can be performed here
// ...
// If all checks pass, the data is considered valid
System.out.println("Valid data" + "\n");
}
// Call the validate function with your input string
Please note that this code provides basic validation for date and time separation. You can add further checks based on your requirements after the arrays are created. The issue you mentioned about the "return" statement being unnecessary is because you are using a "void" method. If you want to return values, consider changing the method's return type to something other than "void."
英文:
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 !!
答案1
得分: 2
另一个答案已经很好地描述了验证日期的更好方法。
我个人认为它未能解决您的担忧:为什么IntelliJ IDEA报告"‘return’ 在‘void’方法的最后一个语句中是不必要的",针对你的一些return语句?
为了解释这一点,我简化了您的示例到这样:
public static void validar(int n) {
System.out.println(n);
if (n == 3) {
System.out.println("a");
return; // 注意1
} else if (n == 5) {
System.out.println("b");
return; // 注意1
}
int x = n * n;
if (x == 4) {
System.out.println("c");
return; // 注意2
} else if (x == 16) {
System.out.println("c");
return; // 注意2
}
}
英文:
The other answer nicely describes better ways to validate dates.
IMHO it fails to address your concern: why does IntelliJ IDEA report "'return' is unnecessary as the last statement in a 'void' method." on some of your return statements?
To explain that, I simplified your example to this:
public static void validar(int n) {
System.out.println(n);
if (n == 3) {
System.out.println("a");
return; // Note 1
} else if (n == 5) {
System.out.println("b");
return; // Note 1
}
int x = n * n;
if (x == 4) {
System.out.println("c");
return; // Note 2
} else if (x == 16) {
System.out.println("c");
return; // Note 2
}
}
I've added two notices to the return statements:
Note 1: the return;
statements at these places is needed to exit early from the method. Without these return;
statements the rest of the method would also execute. Accordingly there is no report from IntelliJ IDEA at these
Note 2: there are no more statements that could possibly be executed after these return;
statements. They are therefore unnecessary. They are the last statements in the branches of an if
- else if
chain and there are no more statements after that chain. That means that execution of the method ends after executing the preceding statement anyway. For these return;
statements IntelliJ IDEA reports "'return' is unnecessary as the last statement in a 'void' method.".
Please note that this is an informational message: its intention is to help you write better (cleaner) code. It doesn't mean that your code is faulty (i.e. it doesn't mean your code will not compile or will have bugs in it.)
You can change that simplified code (without changing its observable behaviour) to
public static void validar(int n) {
System.out.println(n);
if (n == 3) {
System.out.println("a");
return; // Note 1
} else if (n == 5) {
System.out.println("b");
return; // Note 1
}
int x = n * n;
if (x == 4) {
System.out.println("c");
} else if (x == 16) {
System.out.println("c");
}
}
答案2
得分: 0
以下是您要翻译的内容:
"It looks like you are trying to split a string that contains a date. Possibly something like this. 2023-05-11 12:25:32
.
Rather than trying to reinvent the wheel, check out some of these other options.
Option 1: SimpleDateFormat
Why not use SimpleDateFormat
to do the job for you? This method has been around since the beginning and does the job pretty well.
SimpleDateFormat
will attempt to parse the date based on a pattern you define. If it fails to parse, it will throw a checked exception.
public static void validar(String data)
{
DateFormat format = new SimpleDateFormat("yyyy-MM-dd h:mm:ss");
try
{
format.parse(data);
}
catch (ParseException e)
{
System.out.println(e.getMessage());
System.out.println("El format de la data és incorrecte. Comproveu que la data coincideixi amb el format correcte " +
"de \"AAAA-MM-DD hh:mm:ss\"");
}
}
This way you don't need to worry about all of the complicated logic. Instead, you try to parse the date, and if your parse fails, then the date fails validation.
Option 2: Simple Regex
If you aren't concerned with the numbers actually corresponding to a valid date, and just that they match the format you expect, than you can accomplish this via simple pattern matching.
public static void validarRegex(String data)
{
Pattern pattern = Pattern.compile("^\\d{4}\\-\\d{2}\\-\\d{2} \\d{2}:\\d{2}:\\d{2}$");
if (!data.matches(pattern.pattern())) {
System.out.println(data);
System.out.println("El format de la data és incorrecte. Comproveu que la data coincideixi amb el format " +
"correcte " + "de \"AAAA-MM-DD hh:mm:ss\"");
}
}
Option 3: DateTimeFormatter
As user Ole V.V. pointed out, you can also use the updated DateTimeFormatter
to parse the string as well. A word of warning here. The DateTimeFormatter
throws an unchecked exception, so you should be prepared for this behavior. My example below does not catch the exception. You can catch it here, or higher up the chain if you choose.
public static void validar(String data)
{
System.out.println(data);
LocalDateTime.parse(data, DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"));
}
Option 4: Complex Regex
I don't recommend this, because it's nearly impossible to get a good check due to things like leap years. However, if you want to give it a go, there are plenty of examples floating around.
Option 5: String parsing
This is essentially what you are already doing, but a bit more concise.
public static void validate(String data)
{
System.out.println(data);
if (isValidDate(data)) {
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");
}
}
}
public static boolean isValidDate(String data)
{
boolean valid = true;
if (!data.contains(" ")) {
invalidData("No hi ha separació entre data i temps");
valid = false;
}
else if (!data.contains("-")) {
invalidData("La data no conté un guions");
valid = false;
}
else if (!data.contains(":")) {
invalidData("El temps de la data no conté :'s");
valid = false;
}
return valid;
}
public static void invalidData(String message)
{
System.out.println(message);
System.out.println("Data incorrecta" + "\n");
}
英文:
It looks like you are trying to split a string that contains a date. Possibly something like this. 2023-05-11 12:25:32
.
Rather than trying to reinvent the wheel, check out some of these other options.
Option 1: SimpleDateFormat
Why not use SimpleDateFormat
to do the job for you? This method has been around since the beginning and does the job pretty well.
SimpleDateFormat
will attempt to parse the date based on a pattern you define. If it fails to parse, it will throw a checked exception.
public static void validar(String data)
{
DateFormat format = new SimpleDateFormat("yyyy-MM-dd h:mm:ss");
try
{
format.parse(data);
}
catch (ParseException e)
{
System.out.println(e.getMessage());
System.out.println("El format de la data és incorrecte. Comproveu que la data coincideixi amb el format correcte " +
"de \"AAAA-MM-DD hh:mm:ss\"");
}
}
This way you don't need to worry about all of the complicated logic. Instead, you try to parse the date, and if your parse fails, then the date fails validation.
Option 2: Simple Regex
If you aren't concerned with the numbers actually corresponding to a valid date, and just that they match the format you expect, than you can accomplish this via simple pattern matching.
public static void validarRegex(String data)
{
Pattern pattern = Pattern.compile("^\\d{4}\\-\\d{2}\\-\\d{2} \\d{2}:\\d{2}:\\d{2}$");
if (!data.matches(pattern.pattern())) {
System.out.println(data);
System.out.println("El format de la data és incorrecte. Comproveu que la data coincideixi amb el format " +
"correcte " + "de \"AAAA-MM-DD hh:mm:ss\"");
}
}
Option 3: DateTimeFormatter
As user Ole V.V. pointed out, you can also use the updated DateTimeFormatter
to parse the string as well. A word of warning here. The DateTimeFormatter
throws an unchecked exception, so you should be prepared for this behavior. My example below does not catch the exception. You can catch it here, or higher up the chain if you choose.
public static void validar(String data)
{
System.out.println(data);
LocalDateTime.parse(data, DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"));
}
Option 4: Complex Regex
I don't recommend this, because it's nearly impossible to get a good check due to things like leap years. However, if you want to give it a go, there are plenty of examples floating around.
Option 5: String parsing
This is essentially what you are already doing, but a bit more concise.
public static void validate(String data)
{
System.out.println(data);
if (isValidDate(data)) {
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");
}
}
}
public static boolean isValidDate(String data)
{
boolean valid = true;
if (!data.contains(" ")) {
invalidData("No hi ha separació entre data i temps");
valid = false;
}
else if (!data.contains("-")) {
invalidData("La data no conté un guions");
valid = false;
}
else if (!data.contains(":")) {
invalidData("El temps de la data no conté :'s");
valid = false;
}
return valid;
}
public static void invalidData(String message)
{
System.out.println(message);
System.out.println("Data incorrecta" + "\n");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论