Returning a value in Java
How do I write a method which returns a primitive datatype value when inside the method it has an if statement which returns a different datatype depending on the result?
int minimum = 5;
int students = 4;
int studentGrades = 100;
public double getAverage(){
if(students >= minimum){
return studentG开发者_开发知识库rades / students;
}
else {
System.out.println(null, "Sorry, you don't have enough students.");
return false;
}
}
You can't really return two different primitive types from the same method. With reference types you could return Object
, that that isn't a good idea anyway.
Your return false
looks like an error condition, so you might think about throwing an exception here:
public double getAverage(){
if(students >= minimum){
return studentGrades / students;
}
else {
throw new IllegalStateException("not enough students");
}
}
In the example you've given, you should throw an exception - the state of the object isn't valid for the method call, basically. You might want to use IllegalStateException
for this, or choose a different type of exception. (That exception extends RuntimeException
, so it isn't a checked exception. That may or may not appropriate for your real use case.)
(As an aside, the division in your sample code won't do what you want either - you should cast one of the operands to double
if you want it to execute floating point division instead of integer division.)
public Object getAverage()
but then you should check the return class
You can as example return a composite object that contains the score and a flag for success.
Or in the above version you could return Double.NaN
to indicate the failure. Or as others have suggested throw an Exception in case of failure.
I'm no Java expert but I think the good practice here is to throw an exception if you have less than the required amount of students. If you must return 2 completely different values I suggest you encapsulate them in a class of your own.
A java method can have only one return type. So you should try some other approche in handling this situation. As others above have pointed out you could throw a exception. Or you could use a nullable data type, and return null when this special condition is true. But this is ugly and is not recommended.
精彩评论