Reputation: 119
I have a method that will return a String[], depending on previous user input that will determine if the parameter is "INTERNATIONAL" or "DOMESTIC". Regardless, both inputs should lead to the creation of two different String[]. When I try to compile though, I get an "missing return statement" error message. How can I fix this?
Here is my method:
public String[] typeflight(String type)
{
String type2= type.toUpperCase();
if (type2.equals("INTERNATIONAL"))
{
String[] flights = {"B738 to Melbourne, Australia ", "A380 to Beijing, China ", "F348 to London, England ", "M225 to Ontario, Canada",
"E987 to Tokyo, Japan ", "T451 to Copenhagen, Denmark ", "S501 to Seoul, South Korea ", "N778 to Venice, Italy ",
"B621 to Mexico City, Mexico ", "L454 to Rabat, Morocco ", "C998 to San Jose, Costa Rica", "H859 to Amsterdam, Netherlands "};
return flights;
}
else
if(type2.equals("DOMESTIC"))
{
String[] flights = {"459 to Seattle, Washington ", "662 to Los Angeles, California ", "712 to New Orleans, Louisiana ", "285 to Chicago, Illinois ",
"896 to Honolulu, Hawaii ", "476 to Boston, Massachusetts ", "823 to Newark, New Jersey ", "902 to Miami, Florida ",
"353 to Fort Wayne, Indiana ", "112 to Des Moines, Iowa ", "", "294 to Las Vegas, Nevada"};
return flights;
}
}
Thanks in advance!
Upvotes: 0
Views: 118
Reputation: 3560
You should have the return statement for all the cases . So declare the String flights out side the if else and initailize dynmically, and finally return as
public String[] typeflight(String type)
{
String[] flights;
if(condition1){
flights = ....
}
else{
flights = .....
}
return flights;
}
Also you should avoid the declaration of data members in the same name ,
Upvotes: 0
Reputation: 8865
If both the if
conditions fails the function is not returning anything. So return null
if both the conditions don't match.
public String[] typeflight(String type)
{
String type2= type.toUpperCase();
if (type2.equals("INTERNATIONAL"))
{
// Code
return flights;
}
else
if(type2.equals("DOMESTIC"))
{
// Code
return flights;
}
return null;
}
Upvotes: 2
Reputation: 1361
Well compiler need an outside "return statement" to determine return results.
Upvotes: 0
Reputation: 2553
Your issue is that you have an if
and and else if
, but no else
. Java is complaining that the case where type2
does not equal either of the two given values is not addressed.
Upvotes: 0
Reputation: 36456
What happens if neither of those if-statements is true? Then your method has no return value.
e.g. type2 = "ALIEN"
Perhaps there is logic in your program that prevents this from happening. But the Java compiler does not know this.
A quick and dirty fix for this is to just put a return null;
at the end of the method. A "better" way is to use exceptions for illegal arguments.
Upvotes: 4