I'm creating a function that converts minutes to hours and minutes, but I'm doing it this way:
public String duracion(int tiempo) {
int horas = tiempo / 60;
int minutos = tiempo % 60;
return horas + " hrs. " + minutos + " min.";
}
what I want is to return this string:
return ("%d:%02d", horas, minutos);
But I get the error:
Syntax error on token "return", Name expected after this token
But if I use the expression ("%d:%02d", horas, minutos)
with System.out.println
if it works, but I don't want a function void
, I want it to return the text string.
First of all, I don't think this will work for you:
Since the println method in no case accepts 3 parameters, in any case I assume that you have done it with the method
printf
Clarified that, the method
duracion
returns a String, and you are returning an expression that is not valid in Java, you are returning 3 things separated by spaces and all of it enclosed in parentheses.I understand that you are doing all this to be able to do something like this:
The thing is that in Java you can't pass 3 parameters to a function just like that. You have several options.
You can make several functions, for each parameter that you are going to pass to printf, for example:
You can also make a function that returns three different things in a list in an array, for example:
You can also return an object containing all three parameters:
You can also return the string already formatted, and not call printf, but println:
The format function works similar to printf, but it doesn't print it directly, it saves it to a string, and then you do whatever you need with it.
You are forgetting to use the String.format method