Answer the question
In order to leave comments, you need to log in
Why do you still need return?
Hello everyone, do I understand correctly that return is needed in order to transfer the result of the method's actions to the calling class? And if so, why is return needed in the code below? After all, even without returning data, the code will work. I don't quite understand, please explain.
public class Program{
public static void main (String args[]){
daytime(7); // Good morning
daytime(13); // Good after noon
daytime(32); //
daytime(56); //
daytime(2); // Good night
}
static void daytime(int hour){
if (hour >24 || hour < 0)
return;
if(hour > 21 || hour < 6)
System.out.println("Good night");
else if(hour >= 15)
System.out.println("Good evening");
else if(hour >= 11)
System.out.println("Good after noon");
else
System.out.println("Good morning");
}
}
Answer the question
In order to leave comments, you need to log in
The return statement, as its name suggests, returns a result or control from a method.
PS It's amazing that you've been asking Java questions since 2018 and still haven't mastered the very basics.
Specifically, this code does not require a return, because it violates the Single Responsibility Principle. The daytime method in your case is responsible for 2 actions at once - determining what we output and its output. It would be correct to have the following code:
static String daytime(int hour){
if (hour >24 || hour < 0)
throw new IllegalArgumentException("Bad argument");
if(hour > 21 || hour < 6)
return "Good night";
else if(hour >= 15)
return "Good evening";
else if(hour >= 11)
return "Good after noon";
else
return "Good morning";
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question